+92 332 4229 857 99ProjectIdeas@Gmail.com

Exception Handling In Java


Exception:
An exception is an event that describes an unusual or erroneous situation at runtime.
Exceptions are wrapped up as objects.
A program can deal with an exception in one of three ways:
Ignore it
Handle it where it occurs.
Handle it another place in the program.

Exception Types:
Unchecked
Subclasses of RuntimeException and Error.
Does not require explicit handling
Run-time errors are internal to your program, so you can get rid of them by debugging your code
For example, null pointer exception; index out of bounds exception; division by zero exception; ...
Checked
Must be caught or declared in a throws clause.
Compile will issue an error if not handled appropriately.
Subclasses of Exception other than subclasses of RuntimeException.
Other arrives from external factors, and cannot be solved by debugging.
Communication from an external resource – e.g. a file server or database.

Exceptions handled in Java:
Basic Java exception handling is managed via keywords: try, catch, finally, throw, throws.
     
       try block

Code that could generate errors put in try blocks.
       catch block
Code for error handling enclosed in a catch clause.
 finally block
           The finally clause always executes.
           Resources that are opened may need to be closed during                
           Appears after the last catch block.
           It will not execute if System.exit(0)occurs first
  throw
           To manually throw an exception, use the keyword throw.
  throws
           throws exception out of the method, requiring it to be caught and handled by an appropriate exception handler
Any exception that is thrown out of a method must be specified as such by a throws clause.

Syntax:

try {
            // write code that could generate exceptions
       } catch ("Type of Exception To Be Caught") {
            //write code for exception handling
       } catch ("Type of Exception To Be Caught") {
            //code for exception handling, there can be multiple catch, you should write exceptions in a class hierarchy see below example
       } finally {
            //any clean-up code, release the acquired resources
       }


For Example:


       try {
           String line = null;
 //if abc.txt is not found by compiler then it would throw FileNotFoundException, and if you don’t write BufferedReader in try catch it won’t let you compile and throw an IOException as well, and force you to write BufferedReader in try catch block
    BufferedReader br = new BufferedReader(new FileReader("abc.txt"));
    line = br.readLine();
             while(line != null) {
              System.out.println(line);
              line = br.readLine();
            }
       } catch (FileNotFoundException e) {//child class should be writes up
              e.printStackTrace();
       } catch (IOException ioEx) {
              ioEx.printStackTrace();
       } catch (Exception ex) {//is a parent class of all exceptions so writes it in the end
                                 ex.printStackTrace();
       } finally {
             //close BufferedReader object here, br.close();
       }


throw Example:
String letter = null;
             
       if(letter.equals("")) {
                    
              throw new NullPointerException("The String Is Null");
       }
                Exception is thrown because letter contains “null” showing message “The String Is Null”.
String letter = "veracious";
             
       if(letter.equals("")) {
                    
              throw new NullPointerException("The String Is Null");
       }
               Exception is not thrown because now letter contains “veracious”


throws Example:
Method doesn’t want to handle exception itself
it throws the exception, the caller should handle this exception or throws the exception itself

For example:

public static void main(String[] args) throws IOException {
         
   BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
          String readLine = br.readLine();
          System.out.println(readLine);
    }

For example 2:

 public void method1() {
          try {
              method2();
          } catch (FileNotFoundException e) {
              e.printStackTrace();
          } catch (IOException e) {
              e.printStackTrace();
          }
 }
      
//These exceptions will be handled by method1() not method2()
public void method2() throws FileNotFoundException,IOException {
       BufferedReader br = new BufferedReader(new FileReader("abc.txt"));
       String readLine = br.readLine();
       System.out.println(readLine);
}

0 comments: