Wednesday, February 12, 2014

Java / Exception

There are three exceptions components:
- try
- catch
- finally

First example demonstrate what will happen when we don't use exception handling.

public class Main 
{
 public static void main(String[] args)
 { 
  int a = 10;
  int b = 0;
  float result;
  result = a / b;    
  
  System.out.println("Program end");
 }    
}

Output:
Exception in thread "main" java.lang.ArithmeticException: / by zero
 at test.Main.main(Main.java:45)

Program fails.

Second example demonstrate program with exception handling.
public class Main 
{
 public static void main(String[] args)
 { 
  int a = 10;
  int b = 0;
  float result;
  
  try 
  {
   result = a / b;   
   System.out.println(result);
  }
  catch (ArithmeticException e) 
  {
   System.out.println("Exception catched:");   
      e.printStackTrace();
  }
  finally
  {
   System.out.println("Block finally");
  }
  
  System.out.println("Program end");
 }    
}

Output:

Exception catched:
java.lang.ArithmeticException: / by zero
 at test.Main.main(Main.java:48)
Block finally
Program end

Exception catched.
Program didn't fails and run to the end.


TIP: Sequence of block is important!
// That code will couse error - code will not compile
try {

} 
catch (Exception e) {
    
} 
catch (ArithmeticException e) {
    
}

Output:

Unresolved compilation problems: 
Unreachable catch block for ArithmeticException. It is already handled by the catch block for Exception


TIP: Block finally is optional. Never mind whether Exception will occur (will be catched) or not. Block finally will execute everytime.

No comments: