Skip to content
February 23, 2009 / Narayan

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:

public class Student {
//attribute
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 method
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
}

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.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: