Home | Ajax | BioInformatics | Dojo | EAI | EJB | Hibernate | J2ME | Java | Java Glossary | Java Servlets | JavaScript | Jboss | JDBC | JDO | Jmeter | JSF | JSP | JUnit | Maven | MySQL | Spring Framework | SQL | Struts | Technology | WAP | Web Services | XML
 
 
Search All Tutorials

 
Programming Tutorials: Ajax | Articles | JSP | Bioinformatics | Database | Free Books | Hibernate | J2EE | J2ME | Java | JavaScript | JDBC | JMS | Linux | MS Technology | PHP | RMI | Web-Services | Servlets | Struts | UML
 
Java
  JDO Tutorials
  EAI Articles
  Struts Tutorials
  Java Tutorials
  Java Certification
  Java Applet
Questions
Comments

Java Catching and Handling Exceptions

                         

The various keywords for handling exceptions are below.

  • try

  • catch

  • finally

  • throw

  • throws

The three exception handler components are used to catch and handle the exceptions. These are try, catch and finally clause. The mechanism to catch an exception in Java is to use try and catch block. Every catch block can handle only one type of exception however you can use more than one catch clause in a single try block. Simply a statement is surrounded by the try block that may cause the exception to occur. Then the try block is followed by the catch block. And if the exception occurs then this catch block specifies a code that should be executed. 

Using try and catch:-

The syntax for the usage of try, catch and finally block is given below.

try{
       ………
       ………
}
catch(<exceptionclass1> <obj1>){
       ………
       ………
}
finally{
       ………
       ………

 

For using an exception handler in an application, the first step we need to do is to enclose the code that is likely to generate an exception inside a try block. If an exception occurs in the try block then it is handled by the exception handler associated with it. For doing this we need to have one or more catch blocks after the try block, where each catch block acts as an exception handler and can handle the type of exception indicated by its arguments.

 

Lets have a look at the example which shows the implementation of the try, catch and finally block. Here we have used "fis = new FileInputStream (new File (args[0]));" which throws an exception if we write a name of a file which doesn't exist as shown in the output.

 

import java.io.*;

class Test{
public static void main(String args[])throws IOException {
FileInputStream fis=null;
try{
fis = new FileInputStream (new File (args[0]));
}
catch (FileNotFoundException e){
System.out.println("File not found!");
}
finally{
fis.close();
}
}
}

Output of program:

C:\Roseindia\vinod\Exception>javac  Test.java

C:\Roseindia\vinod\Exception>java  Test
File not found!

Download this example

The code which is to be executed in a try block indicates that it will throw an exception. And if the exception occurs then the runtime system checks whether the exception thrown by try block matches to the one in catch clause or not. If yes, then the code within the catch clause gets executed which actually handles the exception. 

Using final: It is always a good practice to use finally clause after the try and catch block because the finally block always executes even if an unexpected exception occurs i.e. whether or not an exception thrown. The finally block executes if and only if the try block exits. Other than exception handling the finally clause helps you in avoiding any cleanup code accidentally bypassed by a return etc. The statements within the finally block gets executed by the the runtime system  without taking care of what happens within the try block.  

There are two steps to use the finally clause:

  • First, you need to enclose the code in a try block that has multiple exit points.

  • Secondly after the try block exits place the code that must be executed in a finally clause. 

Same way we have used the finally block which will execute after the try and catch block.

import java.io.*;

class Test{
public static void main(String args[]){
FileInputStream fis=null;
try {
fis = new FileInputStream (new File (args[0]));
int ch;
while ((ch = fis.read()) != -1){
System.out.print ((char) ch);
}
}
catch (FileNotFoundException e){
System.out.println("File not found!");
}
catch (IOException e){
System.out.println("Unable to read file!");
}
finally{
System.out.println();
System.out.println("In finally.");
try{
if(fis!=null){
fis.close();
}
}
catch (IOException ioe){
System.out.println("In finally.");
}
}
}
}

Output of program:

C:\Roseindia\vinod\Exception>javac  Test.java

C:\Roseindia\vinod\Exception>java  Test abc
File not found!

In finally.

Download this example

Using throws: The other way to handle an exception is using the throws clause. When you call a method from the java API that throws a checked exception, you must either throw the exception or catch it. If you decide that you can't handle the exception properly, then the exception can be declared to the method header using the throws keyword  followed by the class name of the exception. 

You might have come across the throws IOException clause in the method header. For example System.in.read() will give a compile error for IOException. Add the throws clause to the surrounding method to pass the error up to the next level (or else write your own catch/try handler). This clause is placed between the parameter list and the starting of the opening brace of the method. We use this clause when we know that a particular exception may occur. Then instead of terminating the program the compiler throws the exception.

While the throw keyword (note the singular form) is used to force an exception. It can also pass a custom message to your exception handling module. for example:-

throw new FileNotFoundException("Could not find books.txt");

The syntax for coding the throws clause of a method is as:-

method declaration throws Exception1,[Exception2] .......{ }

Likewise we have used throws clause to the method header as "throws FileNotFoundException,IOException " which throws an exception as shown in the output. 

import java.io.*;

class Test3{
public static void main(String args[]) throws FileNotFoundException,IOException {
FileInputStream fis=null;
fis = new FileInputStream (new File (args[0]));
int ch;
while ((ch = fis.read()) != -1){
System.out.print ((char) ch);
}
fis.close();
}
}

Output of program:

C:\Roseindia\vinod\Exception>javac  Test3.java

C:\Roseindia\vinod\Exception>java  Test3
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at Test3.main(Test3.java:6)

Download this example

 

                         

Facing Programming Problem?
Add This Tutorial To:
  Del.icio.us   Digg   Google   Spurl   Blink   Furl   Simpy   Y! MyWeb 

Current Comments

2 comments so far (post your own) View All Comments Latest 10 Comments:

Good Work.The details are crystal clear.

Posted by Priya Rajarajan on Thursday, 05.8.08 @ 23:19pm | #58957

The material provided is really very good to just see certain points quicklly.

Posted by Y.Lakshmi thanuja on Thursday, 01.3.08 @ 11:19am | #44421

Leave your comment:

Name:

Email:

URL:

Title:

Comments:


Enter Code:

 

Note: Emails will not be visible or used in any way, and are not required. Please keep comments relevant. Any content deemed inappropriate or offensive may be edited and/or deleted.

No HTML code is allowed. Line breaks will be converted automatically. URLs will be auto-linked. Please use BBCode to format your text.

Hot Web Programming Job

Java String toLowerCase Example
Java String toCharArray Example
Java String substring Example
Java String indexOf Example
Java String startsWith Example
Java String hashCode Example
Java String matches Example
Java String length Example
Java String lastIndexOf Example
Java String isEmpty Example
Java String equalsIgnoreCase Example
Java String equals Example
Java String endsWith Example
Java String copyValueOf Example
Java String contentEquals Example
  EAI Articles
  Java Certification
Tell A Friend
Your Friend Name
Search Tutorials

 

 
 
Browse all Java Tutorials
Java JSP Struts Servlets Hibernate XML
Ajax JDBC EJB MySQL JavaScript JSF
Maven2 Tutorial JEE5 Tutorial Java Threading Tutorial Photoshop Tutorials Linux Technology
Technology Revolutions Eclipse Spring Tutorial Bioinformatics Tutorials Tools SQL
 

Home | JSP | EJB | JDBC | Java Servlets | WAP  | Free JSP Hosting  | Search Engine | News Archive | Jboss 3.0 tutorial | Free Linux CD's | Forum | Blogs

About Us | Advertising On RoseIndia.net  | Site Map

India News

Send your comments, Suggestions or Queries regarding this site at roseindia_net@yahoo.com.

Copyright © 2007. All rights reserved.