Professional Documents
Culture Documents
16.exception Handling - Throws, Finally and User Defined Exception
16.exception Handling - Throws, Finally and User Defined Exception
TestFinallyBlock.java
class TestFinallyBlock {
public static void main(String args[]){
try{
//below code do not throw any exception
int data=25/5;
System.out.println(data);
}
//catch won't be executed
catch(NullPointerException e){
System.out.println(e);
}
//executed regardless of exception occurred or not
finally {
System.out.println("finally block is always executed"); }
System.out.println("rest of the code..."); } }
When an exception occurr but not handled by the catch block
Sometimes, the built-in exceptions in Java are not able to describe a certain
situation. In such cases, the user can also create exceptions which are called ‘user-
defined Exceptions’.
The following steps are followed for the creation of a user-defined Exception.
The user should create an exception class as a subclass of the Exception class. Since
all the exceptions are subclasses of the Exception class, the user should also make
his class a subclass of it. This is done as:
MyException(){}
MyException(String str)
{
super(str);
}