We have already learnt about the exception handling basics and different types of exception handling in java programming.
Try Catch Block :
We need to put code inside try block that might throw an exception. Try block must be within a method of a java class.
try { //Statement 1; //Statement 2; //Statement 3; }catch(Exception e) { //Exception Handling Code }
above is the syntax of try catch block in java. If an exception occurred during the execution of Statement 1..3 then it will call exception handling code.
Tips for Try-Catch Block :
- The code within try block may or may not raise an exception. If Try block does not throw any exception then catch block gets executed.
- The catch block contains an exception handler and some statements used to overcome that exception
- Each and every Try Block must have catch or finally statement associated with it.
Try Block Present | Catch Block Present | Finally Block Present | Legal Statement |
---|---|---|---|
Present | Present | - | Legal/Complete Try Block |
Present | - | Present | Legal/Complete Try Block |
Present | - | - | Illegal/Incomplete Try Block |
Explanation with Example :
public class ExceptionExample { public static void main(String[] args) { int number1 = 50; int number2 = 0; int result; try { result = number1 / number2; System.out.println("Result of Division : " + ans); } catch(ArithmeticException e) { System.out.println("Divide by Zero Error"); } } }
Consider the above example – We know that division of any number with zero is not possible.If we attempt to divide any number by zero in java then it may cause an error.
result = number1 / number2;
above statement may cause an exception so we need to put that code inside try block. Whenever an exception occures the catch block gets executed.
} catch(ArithmeticException e) { System.out.println("Divide by Zero Error"); }
Inside catch we have simply displayed an error message i.e “Divide by Zero Error”.
Exception thrown and Type of Exception Object :
Exception thrown by try block is of type Arithmetic Exception so it can be catched inside the catch block because we have provided the handler of same type.
try { result = number1 / number2; System.out.println("Result of Division : " + ans); }catch(FileNotFoundException e) { System.out.println("Divide by Zero Error"); }
If we execute the above code instead then thrown exception is of type Arithmetic Exception and Exception Type provided into Catch block is of type FileNotFoundException then exception may not be catched. Thus above code can cause compile time error.
try { result = number1 / number2; System.out.println("Result of Division : " + ans); }catch(Exception e) { System.out.println("Divide by Zero Error"); }
In the above code we can catch all types of exception because Exception is superclass of all the exceptions. [Refer the Exception Hierarchy]
The post Try-Catch Block : Exception Handling in Java Programming appeared first on Learn Java Programming.