Exception are errors occurred during run time and which can be traced and handled. If an exception is occurred then our program unexpectedly close showing some error message and unexpected output. Theses errors my occur internally in the program code or through the resources the program is trying to access. The sources of errors may be user-input errors such as giving a wrong value, device errors such as printer not found, physical limitations such as disk full or memory not enough and code errors like array index out of bound. Java provides appropriate mechanism to handle exceptions. The main purpose of handling exception is to inform the user about the error or to take an alternative path to overcome the problem and complete the remaining task.
In Java we handle exception by using try..catch mechanism. Java provides try, catch and finally keywords for handling exception. The program statements that are supposed to generate or produce error and included inside the try block and the statement that handle the error and produce required information are included inside the catch block. The finally block include those statement that has to be executed whether an error occur or not.
Structure of try, catch and finally keyword
The following program produces divide by zero exception.
Output:
Exception Occured!
java.lang.ArthmeticException: / by zero
In Java we handle exception by using try..catch mechanism. Java provides try, catch and finally keywords for handling exception. The program statements that are supposed to generate or produce error and included inside the try block and the statement that handle the error and produce required information are included inside the catch block. The finally block include those statement that has to be executed whether an error occur or not.
Structure of try, catch and finally keyword
try{
statements that may produce exceptions.
}
catch(ExceptionType ex1){
statements to handle exception of type ExceptionType
}
finally{
statements to be executed whether an exception occurs or not.
}
statements that may produce exceptions.
}
catch(ExceptionType ex1){
statements to handle exception of type ExceptionType
}
finally{
statements to be executed whether an exception occurs or not.
}
The following program produces divide by zero exception.
ExceptionDemo.java
class ExceptionDemo{
public static void main(String[] args){
try{
int x = 10/0;
System.out.println(x);
}
catch(Exception ex){
System.out.println("Exception Occured!");
System.out.println(ex);
}
}
}
class ExceptionDemo{
public static void main(String[] args){
try{
int x = 10/0;
System.out.println(x);
}
catch(Exception ex){
System.out.println("Exception Occured!");
System.out.println(ex);
}
}
}
Output:
Exception Occured!
java.lang.ArthmeticException: / by zero
No comments:
Post a Comment