The Java language has classes that handle cases where problems arise during program execution. The problem is called an exception or an error. They will normally deter further execution of the program, either because it is not possible to do so, or erroneous results will be produced. Exceptions are unexpected problems that can be corrected and execution continued, along the same or a different path. Some exceptions are checked by Java during execution (files not found, IO errors, etc.), these are called checked exceptions. Others are not checked by Java, mostly because it is too expensive on resources to check exceptions that can be prevented by proper program logic (division by zero, array out of bound, etc). These are called unchecked exceptions. Errors problems that render further execution not meaningful. They include out of memory situations, thread death, etc. However, when this happens, it is useful to release resouces before program termination to prevent resource locking. File closure, memory release, etc. are examples. When a Java program instantiates an exception handling object, it is said to THROW an exception. The part of the code where Java generates code to detect specific kinds of exception is called a CATCH clause. Error and Exception make up the the sub-classes derived from the class called Throwable. Each of these classes has a number of subclasses to handle various exception conditions. Refer to the Java documentation for details. The program structure in Java to handle exceptions is called a try-catch-finally clauses, as follows:
try{ ...some code that might throw exceptions } catch(exception_type){ ...error processing code } catch(exception_type){ ...error processing code } finally{ ...resource release, this always executes }
The following code illustrates the try-catch-finally structure, with text output to trace the execution paths. Three cases are implemented: 1. An arithmetic division by zero exception (unchecked, but can be handled) 2. A general exception (checked, MUST provide handler) 3. Array-out-of-bounds exception (unchecked, but can be handled). Note that the first and third exceptions are sub-class objects of Exception, and hence MUST be caught before. Failure to do so will produce a compilation error.
Code:
// Exceptions, demonstrates hierarchy, and order of Catch clauses
//
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class Except extends JFrame implements ActionListener{
final int iSize=20;
JButton bArith=new JButton("ArithmeticException");
JButton bExcept=new JButton("Exception");
JButton bArray=new JButton("Array");
JTextArea out=new JTextArea("",14,45);
int arr[]={1,2,3,4};
public Except(){
super("Exceptions");
// GUI Stuff
Container c=getContentPane();
c.setLayout(new FlowLayout());
c.add(bArith); c.add(bExcept); c.add(bArray);
bArith.addActionListener(this);
bExcept.addActionListener(this);
bArray.addActionListener(this);
JScrollPane scr=new JScrollPane(out);
out.setFont(new Font("Courier",Font.BOLD,12));
c.add(scr);
setLocation(50,250);
setSize(350,350);
setVisible(true);
}
private void Test(int Denominator) throws Exception, ArithmeticException{
// note that Arithmetic Exception is an unchecked exception, so it is
// NOT required to be appended to the throws clause
// On the other hand, Exception must be included in the throws clause
// because Exception includes both checked and unchecked exceptions.
int a=2;
if(Denominator==0){
a/=Denominator;
} else {
a/=Denominator;
throw new Exception();
}
}
public void actionPerformed(ActionEvent event){
try{
out.append("=================\nEntering method Test\n");
if(event.getSource()==bArith)Test(0);
else if(event.getSource()==bExcept)Test(1);
else if(event.getSource()==bArray)arr[4]=1;
}
catch(ArithmeticException e){
// by catching ArithmeticException, which has a lower hirarchy,
// the error message is more specific
out.append(e.toString()+"\n");
}
catch(RuntimeException e){
// ArrayIndexOutOfBoundsException is a subclass of RunTimeException
out.append(e.toString()+"\n");
}
catch(Exception e){
// Exception is a general exception, and often does not reveal too
// much information to the user.
// It is a compilation error to place this catch clause before
// the subclass ArithmeticException.
out.append(e.toString()+"\n");
}
finally{
// This clause is for relasing resources
out.append("Finally executed\n");
}
}
}
public class Exceptions{
public static void main(String[] args){
Except g=new Except();
}
}