Exception handling – try catch
One of the ways of handling exception in java is by using Try-catch block.
Syntax for using try & catch
- try{
- Normal statement(s)
- }
- catch (exceptiontype name){
- Exception handling statement(s)
- }
try{ Normal statement(s) } catch (exceptiontype name){ Exception handling statement(s) }
We place normal code that might throw an exception in Try block and Exception handling code in Catch block
Example :
Consider below example
- package com.kb.state;
- import java.util.Scanner;
- public class ExceptionTryCatchExample {
- public static void main(String args[])
- {
- int dividend = 8;
- int divisor = 0;
- float result = 0;
- result = dividend/divisor;
- System.out.println("Result is " +result);
- }
- }
package com.kb.state; import java.util.Scanner; public class ExceptionTryCatchExample { public static void main(String args[]) { int dividend = 8; int divisor = 0; float result = 0; result = dividend/divisor; System.out.println("Result is " +result); } }
The above program throws an exception and we need to handle it
We know that the line causing the exception is
- result = dividend/divisor;
result = dividend/divisor;
We need to place such lines in a Try-catch block
Let’s handle this exception using Try-catch block as below
- package com.kb.state;
- import java.util.Scanner;
- public class ExceptionTryCatchExample {
- public static void main(String args[])
- {
- int dividend = 8;
- int divisor = 0;
- float result = 0;
- try {
- result = dividend/divisor;
- System.out.println("Result is " +result);
- } catch (Exception e) {
- System.out.println("Can not perform dvision as Divisor is Zero");
- }
- System.out.println("End of Program");
- }
- }
package com.kb.state; import java.util.Scanner; public class ExceptionTryCatchExample { public static void main(String args[]) { int dividend = 8; int divisor = 0; float result = 0; try { result = dividend/divisor; System.out.println("Result is " +result); } catch (Exception e) { System.out.println("Can not perform dvision as Divisor is Zero"); } System.out.println("End of Program"); } }
We can see that because of exception handling using Try-catch, our program is continuing further execution even after the exception.