Vous êtes sur la page 1sur 18

EXCEPTIONS

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

Exceptions that are NOT


subclasses of
RuntimeException are
checked for by
the compiler. They’re
called
“checkedexceptions”
Error
Exception

InterruptedException
RuntimeException
IOException

RuntimeExceptions are NOT


NullPointerException checked by the compiler.
ArithmeticException They’re known as
“unchecked exceptions”. You
can throw, catch,and declare
RuntimeExceptions, but you
don’t have to, and the
compiler won’t check

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

Divide by zero java.lang.ArithmeticException: / by zero


Statement after catch block

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)

When the program is run for the second time:


The user enters “0” as an input

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

When an exception occurs , the nearest corresponding catch block whic


whichh matches the exception
thrown( in try block) is executed by the JVM and rest of the catch blocks are skipped

Exception... Division by zero


“The result is : 0
java.lang.ArithmeticException: / by zero
atMultipleCatch.main(MultipleCatch.java:13
Catch.main(MultipleCatch.java:13)

e.printStackTrace(); statement is responsible for printing the exception


stack at last.

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.

Thus, a subclass would never be reached if it came after its superclass.

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

C:\cse\SuperSubCatch.java:16: exception java.lang.ArithmeticException has already been


caught
catch(ArithmeticExceptionae)
1 error

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 }

Incorrect argument type: Enter integer divide by zero Exception

7
throw

try-throw-catch“throw” is used to manually throw an exception (object) of type Throwable


class or a subclass of Throwable. Simple types, such as int or char, as well as non-
Throwable classes, such as String and Object, cannot be used as exceptions. The flow of
execution stops immediately after the throw statement; any subsequent statements are
not executed.

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.*;

public class ReadingFile


{
public static void main(String args[])
{
String file = "C:\\cse\\FibonacciRec.java"; 1
try
{
FileReader fr = new FileReader(file); 2
if(fr == null)
throw new FileNotFoundException("File Not Found Exception has occured"); 3

BufferedReader br = new BufferedReader(fr);


String s;
int i = 1;

while (((s = br.readLine()) != null))


{
System.out.println(i + " " + s);
i++;
}
}
catch(FileNotFoundException fne) 4
{
System.out.println(fne);
System.out.println(file+"File Does Not Exist");
}
catch(IOException io)
{
System.out.println("IOException has occured");
}
}
}
java.io.FileNotFoundException: C:\cse\FibonacciRec.java (The system cannot find the path specified)

C:\cse\FibonacciRec.javaFile Does Not Exist

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.

public class ReadFile


{
public void openFile() throws FileNotFoundException, IOException 2
{
String file = "C:\\cse\\FibonacciRec.java";

System.out.println("File Not Found Exception will be raised");


3 FileReader fr = new FileReader(file);

BufferedReader br = new BufferedReader(fr);


String s;
int i = 1;

while (((s = br.readLine()) != null))


{
System.out.println(i + " " + s);
i++;
}
}
}

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);
}
}
}

File Not Found Exception will be raised


Exception raised in openFile() is caught here
java.io.FileNotFoundException: C:\cse\FibonacciRec.java (The system cannot find the path pecified)
File does not exist

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");
}
}

// Return from within a try block.


static void procB() {
try {
System.out.println("inside procB");
return;
} finally {
System.out.println("procB's finally");
}
}
// Execute a try block normally.
static void procC() {
try {
System.out.println("inside procC");
} finally {
System.out.println("procC'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

EXCEPTION RESUMPTION MODEL.

import java.util.*;

public class ExceptionRecovery {


public static void main(String args[]){
Scanner sc = new Scanner(System.in);
int number = 0; If nextInt throws an exception, the
boolean isCorrectInput = false; try block ends and so the boolean
do variable isCorrectInput is not set to
{ true and the user is given another
try chance to enter the input
{
System.out.println("Enter an integer");
number = sc.nextInt();
isCorrectInput = true;
}
catch(InputMismatchException iae)
{ sc.nextLine();
System.out.println(iae);
System.out.println("Not a number.---Try again\n");
}
}
while( isCorrectInput == false);
System.out.println("You have entered correct input= " + number );
}
}
OUTPUT
Enter an integer:java
java.util.InputMismatchException
Not a number.---Try again

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 class NegativeAgeException extends Exception {

private int age;

public NegativeAgeException(int age) {


4 this.age = age;
}

public NegativeAgeException() {
super("Age cannot be negative");
}

public String toString() {


return "Age cannot be negative " + age;
}
}

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.

// Demonstrate exception chaining.


class ChainExcDemo {

static void demoproc() {


// create an exception
NullPointerException e =
new NullPointerException("top layer");
// add a cause
e.initCause(new ArithmeticException("cause"));
throw e;
}

public static void main(String args[]) {


try {
demoproc();
} catch (NullPointerException e) {
// display top level exception
System.out.println("Caught: " + e);
// display cause exception
System.out.println("Original cause: " +
e.getCause());
}
}
}

Caught: java.lang.NullPointerException: top layer


Original cause: java.lang.ArithmeticException: cause

13
ERROR
java.lang
Class Error
java.lang.Object
java.lang.Throwable
java.lang.Error
All Implemented Interfaces:

Serializable

Direct Known Subclasses:

AssertionError, AWTError, CoderMalfunctionError, FactoryConfigurationError, LinkageError,


ThreadDeath, TransformerFactoryConfigurationError, VirtualMachineError

public class Error

extendsThrowable

An Error is a subclass of Throwable that indicates serious problems that a reasonable


application should not try to catch. Most such errors are abnormal conditions. The ThreadDeath
error, though a "normal" condition, is also a subclass of Error because most applications should
not try to catch it.

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(String message, Throwable cause)


Constructs a new error with the specified detail message and cause.

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

AssertionError LinkageError ThreadDeath VirtualMachineError

Unchecked exceptions :

 representdefects in the program (bugs) - often invalid arguments passed to a


non-private method. To quote from The Java Programming Language, by
Gosling, Arnold, and Holmes : "Unchecked runtime exceptions represent
conditions that, generally speaking, reflect errors in your program's logic and
cannot be reasonably recovered from at run time."
 are subclasses of RuntimeException, and are usually implemented using
IllegalArgumentException, NullPointerException, or IllegalStateException
 a method is not obliged to establish a policy for the unchecked exceptions
thrown by its implementation (and they almost always do not do so)

Checked exceptions :

 represent invalid conditions in areas outside the immediate control of the


program (invalid user input, database problems, network outages, absent
files)

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)

Java’s Built-in Exceptions


The types of exceptions that need not be included in a methods throws list are called
Unchecked Exceptions

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

RuntimeExceptions are NOT checked by the compiler. They’re known as


“unchecked exceptions”. You can throw, catch,and declare RuntimeExceptions, but
you don’t have to, and the compiler won’t check

THE JAVA LANGUAGE


Exception Meaning

ArithmeticException Arithmetic error, such as


divide-by-zero.

ArrayIndexOutOfBoundsException Array index is out-of-bounds.

ArrayStoreException Assignment to an array element of an


incompatible type.

ClassCastException Invalid cast.

IllegalArgumentException Illegal argument used to invoke a


method.

IllegalMonitorStateException Illegal monitor operation, such as


waiting on an unlocked thread.

IllegalStateException Environment or application is in


incorrect state.

16
IllegalThreadStateException Requested operation not compatible
with current thread state.

IndexOutOfBoundsException Some type of index is out-of-bounds.

NegativeArraySizeException Array created with a negative size.

NullPointerException Invalid use of a null reference.

NumberFormatException Invalid conversion of a string to a


numeric format.

SecurityException Attempt to violate security.

StringIndexOutOfBounds Attempt to index outside the bounds of


a string.

UnsupportedOperationException An unsupported operation was


encountered.

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

ClassNotFoundException Class not found.

IllegalAccessException Access to a class is denied.

17
InstantiationException Attempt to create an object of an
abstract class or interface.

InterruptedException One thread has been interrupted by


another thread.

NoSuchFieldException A requested field does not exist.

NoSuchMethodException A requested method does not exist.

18

Vous aimerez peut-être aussi