JAVA | Explain try – catch statement with one example.

An exception is an event which occurs during the execution of a program and disrupts the normal execution of the program. When an exception occurs in a method, it creates an exception object and
hands it to the run time system. The object contains information about the exception. The exception can be handled using try-catch block. 
The code that may create an exception should be enclosed in a try block. If an exception occurs within the try block, an exception object is created of the specific type, and is thrown. That exception is
handled by an exception handler associated with it. To associate an exception handler with a try block, a catch block is specified after try block. A try block can have any number of catch.

Example:
import java.io.*;
class ExceptionHandling {
int num1, num2, answer;
void acceptValues() {  
BufferedReader bin = new BufferedReader(new
InputStreamReader(System.in));
try {
 System.out.println("Enter two numbers");
 num1 = Integer.parseInt(bin.readLine());
 num2 = Integer.parseInt(bin.readLine()); 
} catch(IOExceptionie) {
 System.out.println("Caught IOException"+ie);
} catch(Exception e) {
System.out.println("Caught the exception "+e);
}
void doArithmetic() {
acceptValues();
try {
 answer = num1/num2;
 System.out.println("Answer is: "+answer);
 } catch(ArithmeticExceptionae) {
 System.out.println("Divide by zero"+ae);
 }
}
 public static void main(String a[]) {
 ExceptionHandling e = new ExceptionHandling();
 e.doArithmetic();   
 } 

Post a Comment

0 Comments