Exception Handler

Here we are going to start a exception handler of handling the occurance of error.

To start the exception we must know a few info about the try{} catch() and finally{}.

Try{}
This try helps is to try any operation and if there appears any error then it directly goes to the catch() method to check either the error matches with the exception defined at catch(). If no any catch is found then it directly goes to finally{} method for end of try{} method.

catch()
This catch() method is one of the exception handler method which catches the exception defined in it’s parenthesis.
for eg:
catch(IOException ioExp){}

finally{}
This finally is the last one which is not essential if there is a catch() method. The finally is the end of the try method.

A sample class for try catch:
[sourcecode=’java’]
public class Student {
//ATTRIBUTES
private String name;

//ACCESSOR METHOD
public void setName(String nam){
this.name = nam;
}

public String getName(){
return name;
}

//MAIN METHOD
public static void main(String[] args)throws IOException{
Student s1 = new Student();
Student s2 = null;

//TRY BLOCK
try{
//we are going to instantiate the student method
System.out.println(“Let’s try for student object of s1”);

s1.setName(“Narayan”);
System.out.println(“Let’s try for studnet object of s2”);

s2.setName(“Gopal”);
System.out.println(“We have reached at the end of try method”);

}

//catching the null pointer exception
catch(NullPointerException a){
System.out.println(“It’s a null pointer exception”);

}

//finally
finally{
System.out.println(“Our process is ended”);
}
//end of try

}
//end of main method
}

[/sourcecode]

By the above sample you can see the output like this:

tryOutput info:

The output show that we have completed to invoke the object s1 but when we try to invoke s2 then it shows a error of a null pointer exception and finally our all process is finished.

By the above exception handler we can elaborate catch() as we want in OOPL . This helps in handling he error at java.
A good programmer uses exception’s for more advantages.

Please comment me if there is any thing which i can do for u.

Leave a Reply