Académique Documents
Professionnel Documents
Culture Documents
Exception is an abnormal condition that arises in the program during execution. When such a condition
arises in the program, an appropriate code is written so that it can be handled. It is very much similar to
the error codes returned by a subroutine in the C language. Whatever value the function returns can be
checked, and depending upon the value you can make out whether it is executed successfully or were
there any errors. If there is an error then you need to match the error code with the error list and find
out what error occurred. Java runtime environment has adopted this feature extensively using object-
oriented methodology in the form of exception handling.
By using the exception handling you can prevent your program from abruptly ending, flashing surprising
and annoying error messages. On the contrary, if a minor error crops up it can be handled during runtime
and your program resumes from there on without crashing down.
All exceptions in Java are subclasses of the built-in-class called Throwable. There are two main
subclasses under throwable: Exception and Error.
The Exception class caters to all the problems that should be caught by the user program. Runtime
Exception is an important sub class of Exception; exception of these kinds are predefined such as divided
by zero etc. the exception that are not expected to be caught by user program and more or less fatal in
nature come under the Error subclass, for example stack overflow. These are the catastrophic conditions,
which are dealt by the run time environment itself. Apart from the system-generated exception, the user
also can explicitly define their own exceptions.
1
Object
Throwable
InterruptedException
RuntimeException
IOException
2
USING Try AND Catch : DivideByZeroException
If the try block fails (an exception), flow control immediately moves to the catch block. When the catch block
completes, the finallyblock runs. When the finally block completes, the rest of the method continues on.
If the try block succeeds (no exception),flow control skips over the catch block and moves to the finally block.
When the finally block completes, the rest of the method continues on.
If the try or catch block has a return statement, finally will still run! Flow jumps to the finally, then back to the
return.
1public classDivideByZero {
2
3public staticvoid main(String args[])
4 {
5int a = 10;
6int b = 0;
7
8 try
9 {
10 int z = a / b; 1
11
12 System.out.println("Division result is:");
13 System.out.println( " z = " + z );
14
15 }
16 catch(ArithmeticExceptionae)
17 {
18 System.out.println(" Divide by zero " + ae ); 2
19 ae.printStackTrace();
20
21 }
22 System.out.println("Statement after catch block"); 3
23 }
24 }
OUTPUT
An exception that is not caught eventually causes Java’s default exception handler to run.This displays the name of
the exception, the optional character string that was supplied when the exception was constructed and a complete
execution stack trace. The stack trace shows the complete method call stack. This lets the programmer see the path
of execution that led to the exception file-by-file (and thus class-by-class) and method-by-method. This information
is helpful in debugging a program.
3
MULTIPLE Catch Statements
A single try block can have many catch blocks. This is necessary when the try block has statements that
raise different types of exceptions.
When you use multiple catch statements, it is important to remember that exception subclasses must come before
any of their superclasses. This is because a catch statement that uses a superclass will catch exceptions of that type
plus any of its subclasses
1 // MultipleCatch.java
2 import javax.swing.*;
3
4 public class MultipleCatch {
5
6 public static void main(String args[]) {
7 int array[] = {0, 0};
8 int num1, num2, result = 0;
9 num1 = 100;
10 num2 = Integer.parseInt(JOptionPane.showInputDialog("Enter int"));
11
12 try {
13 result = num1 / num2;
14 System.out.println(num1 / array[2]);
15
16 }
17
18 catch (ArithmeticException e) {
19 System.out.println("Exception... Division by zero");
20 e.printStackTrace();
21 }
22
23 catch (ArrayIndexOutOfBoundsException e) {
24 System.out.println("Exception….out of Bounds");
25 e.printStackTrace();
26 }
27
28 catch (Exception e) {
29 System.out.println("Exception…");
30 }
31
32
33 System.out.println("“The result is : " + result);
34 }
35 }
When the user gives non zero value integer as an input…the catch
handler handling the ArithmeticException is not executed…
At line 14: deliberate attempt has been made to access the array out of bounds which causes the
ArrayIndexOutOfBoundsException to be raised.
4
Exception….out of Bounds
“The result is : 10
java.lang.ArrayIndexOutOfBoundsException: 2
atMultipleCatch.main(MultipleCatch.java:14
ultipleCatch.java:14)
At line 13 of try block an attempt is made to divide the integer with zero value which causes the
ArithmeticException to be thrown.The control flows to the line # 16..and executes the catch block
5
Handling the Unreachable Code Problem
The multiple catch blocks generate unreachable code error. If the first catch block contains the
Exception class object then the subsequent catch blocks are never executed. The exception class being
the super class of all the exception classes catches various types of exceptions.
The java complier gives an error stating that the subsequent catch blocks have not been
reached. This is known as Unreachable code problem. To avoid this, the last catch block in multiple
catch blocks must contain the Exception class object.
When you use multiple catch statements, it is important to remember that exception subclasses
must come before any of their superclasses. This is because a catch statement that uses a
superclass will catch exceptions of that type plus any of its subclasses.
2 //SuperSubCatch.java
3 public class SuperSubCatch {
4
5 public static void main(String args[]) {
6 int a = 10;
7 int b = 0;
8
9 try {
10 int z = a / b;
11 }
12 catch (Exception e) {
13 System.out.println("Exception " + e);
14 }
15
16 catch (ArithmeticException ae) {
17 System.out.println("Divide By zero Error" + ae);
18 }
19 }
20 }
OUTPUT
Compiling 1 source file to C:\Users\Aatika\Documents\NetBeansProjects\Lab\build\classes
6
NESTED try
These try blocks may be written independently or we can nest the try blocks within each other, i.e., keep
one try-catch block within another try-block. The program structure for nested try statement is:
Consider the following example in which you are accepting two numbers from the command line. After
that, the command line arguments, which are in the string format, are converted to integers. If the
numbers were not received properly in a number format, then during the conversion a
NumberFormatException is raised otherwise the control goes to the next try block. Inside this second try-
catch block the first number is divided by the second number, and during the calculation if there is any
arithmetic error, it is caught by the inner catch block.
1 import javax.swing.*;
2
3 class NestedTry {
4
5 public static void main(String args[]) {
6 try
7 {
8 String a = JOptionPane.showInputDialog("Enter a:");
9 int a1 = Integer.parseInt(a);
10
11 String b = JOptionPane.showInputDialog("Enter b:");
12 int b1 = Integer.parseInt(a);
13
14 int quot = 0;
15
16 try
17 {
18 quot = a1 / b1;
19 System.out.println(quot);
20 } catch (ArithmeticException e)
21 {
22 System.out.println("divide by zero Exception");
23 }
24 }
25 catch (NumberFormatException e) {
26 System.out.println("Incorrect argument type:Enter int value");
27 }
28 }
29 }
7
throw
When used together, the try, throw, and catch statements are the basic mechanism for throwing and catching
exceptions. The throw statement throws the exception. The catch block catches the exception. The throw statement is
normally included in a try block. When the exception is thrown, the try block ends and then the code in the catch block
is executed. After the catch block is completed, the code after the catch block(s) is executed (provided the catch block
has not ended the program or performed some other special action).
If no exception is thrown in the try block, then after the try block is completed, program execution continues with the
code after the catch block(s). (In other words, if no exception is thrown, the catch block(s) are ignored.)
import java.io.*;
8
Throws / UNCHECKED EXCEPTION
If a method is capable of causing an exception that it does not handle, it must specify this
behavior so that callers of the method can guard themselves against that exception. You do
this by including a throws clause in the method’s declaration. A throws clause lists the
types of exceptions that a method might throw.
import java.io.*;
public class ReadFileTest
{
public static void main(String args[])
{
ReadFile ln = new ReadFile();
try
{
ln.openFile();
} 1
4 catch(FileNotFoundException fne)
{
System.out.println("Exception raised in openFile() is caught here");
System.out.println(fne);
System.out.println("File does not exist");
}
catch (IOException io)
{
System.out.println(io);
}
}
}
9
Finally
THE finally BLOCK
The finally block contains code to be executed whether or not an exception is thrown in a try block.
The finally block, if used, is placed after a try block and its following catch blocks.
Now, suppose that the try-catch-finally blocks are inside a method definition.
(After all, every set of try-catch-finally blocks is inside of some method, even if it is only the method
main.) There are three possibilities when the code in the try-catch finally blocks is run:
1. The try block runs to the end and no exception is thrown. In this case, the finally block is executed
after the try block.
2. An exception is thrown in the try block and is caught in one of the catch blocks positioned after the
try block. In this case, the finally block is executed after the catch block is executed.
3. An exception is thrown in the try block and there is no matching catch block in the method to
catch the exception. In this case, the method invocation ends and the exception object is thrown to
the enclosing method. However, the finally block is executed before the method ends.
// Demonstrate finally.
class FinallyDemo {
// Through an exception out of the method.
static void procA() {
try {
System.out.println("inside procA");
throw new RuntimeException("demo");
} finally {
System.out.println("procA's finally");
}
}
10
public static void main(String args[]) {
try {
procA();
} catch (Exception e) {
System.out.println("Exception caught");
}
procB();
procC();
}
}
inside procA
procA's finally
Exception caught
inside procB
procB's finally
inside procC
procC's finally
import java.util.*;
Enter an integer: 23
You have entered correct input= 23
11
Creating Your Own Exception SubclassesThough Java provides an
extensive set of in-built exceptions, there are cases in which we may need to define our
own exceptions in order to handle the various application specific errors that we might
encounter.
While defining an user definedexception, we need to take care of the following aspects:
The user defined exception class should extend from Exception class.
The toString() method should be overridden in the user defined exception class in
order to display meaningful information about the exception.
public NegativeAgeException() {
super("Age cannot be negative");
}
import java.io.*;
import java.util.*;
public class AgeExceptionTest
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter age"); 1
int age = sc.nextInt();
try
{
if (age < 0) 2
{
3 NegativeAgeException nae = new NegativeAgeException(age);
throw nae; 5
}
} 6
catch (NegativeAgeException nae) {
System.out.println("Negative Age Exception Caught\n" +nae.toString());
}
}
}
Enter age :2
Negative Age Exception Caught Age cannot be negative -2
12
Chained Exceptions
The chained exception feature allows you to associate another exception with an exception. This second exception
describes the cause of the first exception. Lets take a simple example. You are trying to read a number from the
disk and using it to divide a number. Think the method throws an ArithmeticException because of an attempt to
divide by zero (number we got). However, the problem was that an I/O error occurred, which caused the divisor to
be set improperly (set to zero). Although the method must certainly throw an ArithmeticException, since that is
the error that occurred, you might also want to let the calling code know that the underlying cause was an I/O
error. This is the place where chained exceptions come in to picture.
13
ERROR
java.lang
Class Error
java.lang.Object
java.lang.Throwable
java.lang.Error
All Implemented Interfaces:
Serializable
extendsThrowable
A method is not required to declare in its throws clause any subclasses of Error that might be
thrown during the execution of the method but not caught, since these errors are abnormal
conditions that should never occur
Constructor Summary
Error()
Constructs a new error with null as its detail message.
Error(String message)
Constructs a new error with the specified detail message.
Error(Throwable cause)
Constructs a new error with the specified cause and a detail message of (cause==null ? null
: cause.toString()) (which typically contains the class and detail message of cause).
14
Object
ERROR CLASS HIERACHY
Throwable
Error Exception
Unchecked exceptions :
Checked exceptions :
15
are subclasses of Exception
a method is obliged to establish a policy for all checked exceptions thrown by
its implementation (either pass the checked exception further up the stack,
or handle it somehow)
The most general of these exceptions are subclasses of the standard type
RuntimeException. Since java.langis implicitly imported into all Java programs,
most exceptions derived from RuntimeExceptionare automatically available
16
IllegalThreadStateException Requested operation not compatible
with current thread state.
CHECKED EXCEPTIONS
A checked exception is any subclass of Exception (or Exception itself), excluding class
RuntimeException and its subclasses.Checked exceptions must be caught at compile time
Those exceptions defined by java.langthat must be included in a method’s throws list if that
method can generate one of these exceptions and does not handle it itself. These are called
checked exceptions.
Exception Meaning
17
InstantiationException Attempt to create an object of an
abstract class or interface.
18