Vous êtes sur la page 1sur 14

Exceptions:

An OO Way for Handling


Errors

Introduction
Rarely does a program runs successfully at its
very first attempt.
It is common to make mistakes while developing
as well as typing a program.
Such mistakes are categorised as:
syntax errors - compilation errors.
semantic errors leads to programs producing
unexpected outputs.
runtime errors most often lead to abnormal
termination of programs or even cause the system to
crash.

1
Common Runtime Errors
Dividing a number by zero.
Accessing an element that is out of bounds of an array.
Trying to store incompatible data elements.
Using negative value as array size.
Trying to convert from string data to a specific data value
(e.g., converting string abc to integer value).
File errors:
opening a file in read mode that does not exist or no read
permission
Opening a file in write/update mode which has read only
permission.
Corrupting memory: - common with pointers
And more .

Without Error Handling

class NoErrorHandling{
public static void main(String[] args){
int a,b;
a = 7;
b = 0;
Program does not reach here
System.out.println( Result is + a/b);
System.out.println( Program reached this line );
}
}
No compilation errors. While running it reports an error and stops without
executing further statements:
java.lang.ArithmeticException: / by zero at Error2.main(Error2.java:10)

2
Traditional way of Error Handling
class WithErrorHandling{
public static void main(String[] args){
int a,b;
a = 7; b = 0;
if (b != 0){
System.out.println( Result is + a/b);
}
Program reaches here
else{
System.out.println( B is zero );
}
System.out.println( Program is complete );
}
}

Error Handling
Any program can find itself in unusual
circumstances Error Conditions.

A good program should be able to


handle these conditions gracefully.

Java provides a mechanism to handle


these error condition - exceptions

3
Exceptions
An exception in Java is an object that describes
an unusual or erroneous situation

Exceptions are thrown, and may be caught and


handled

A program can be separated into a normal


execution flow and an exception execution flow

An error is also represented as an object in


Java, but usually represents a unrecoverable
situation and should not be caught
7

Exceptions and their Handling


When the JVM encounters an error such as
divide by zero, it creates an exception object and
throws it as a notification that an error has
occurred.
If the exception object is not caught and handled
properly, the interpreter will display an error and
terminate the program.
If we want the program to continue with
execution of the remaining code, then we should
try to catch the exception object thrown by the
error condition and then take appropriate
corrective actions. This task is known as
exception handling.

4
Uncaught Exceptions
If an exception is not caught by user program, then
execution of the program stops and it is caught by the
default handler provided by the Java run-time system
Default handler prints a stack trace from the point at
which the exception occurred, and terminates the
program

Ex:
class Exc0 {
public static void main(String args[]) {
int d = 0;
int a = 42 / d;
}
}
Output:
java.lang.ArithmeticException: / by zero
at Exc0.main(Exc0.java:4)
Exception in thread "main"

Notice how the class name, Exc0; the method name, main;
the filename, Exc0.java; and the line number, 4, are all
included in the simple stack trace.
Also, notice that the type of the exception thrown is a
subclass of Exception called ArithmeticException, which
more specifically describes what type of error happened.

5
The stack trace will always show the sequence of method
invocations that led up to the error. For example, here is
another version of the preceding program that introduces
the same error but in a method separate from main():

class Exc1{
static void subroutine(){
int d = 0;
int a = 10 / d;
}
public static void main(String args[]){
Exc1.subroutine();
}
}
The resulting stack trace from the default exception
handler shows how the entire call stack is displayed:
Java.lang-ArithmeticException: / by zero at
Exc1.subroutine(Exc1.Java:4) at Exc1.main(Exc1.Java:7)

Java.lang-ArithmeticException: / by zero at
Exc1.subroutine(Exc1.Java:4) at
Exc1.main(Exc1.Java:7)

As you can see, the bottom of the stack is


main's line 7, which is the call to subroutine(),
which caused the exception at line 4. The call
stack is quite useful for debugging, because it
pinpoints the precise sequence of steps that led
to the error.

6
Exception Handling
Java has a predefined set of exceptions and errors that
can occur during execution

A program can deal with an exception in one of three


ways:

ignore it
handle it where it occurs
handle it in another place in the program

The manner in which an exception is processed is an


important design consideration

13

Exception Handling
If an exception is ignored by the program, the
program will terminate abnormally and produce an
appropriate message

The message includes a call stack trace that:

indicates the line on which the exception occurred

shows the method call trail that lead to the


attempted execution of the offending line

14

7
Common Java Exceptions
ArithmeticException
ArrayIndexOutOfBoundException
ArrayStoreException
FileNotFoundException
IOException general I/O failure
NullPointerException referencing a null object
OutOfMemoryException
SecurityException when applet tries to perform an
action not allowed by the browser s security setting.
StackOverflowException
StringIndexOutOfBoundException

Exception handling in Java


Java exception handling is managed via five keywords:
try, catch, throw, throws, and finally.
Program statements that you want to monitor for
exceptions are contained within a try block. If an
exception occurs within the try block, it is thrown.
Your code can catch this exception (using catch) and
handle it. System-generated exceptions are
automatically thrown by the Java run-time system.
To manually throw an exception, use the keyword throw.
Any exception that is thrown out of a method must be
specified as such by a throws clause.
Any code that absolutely must be executed before a
method returns is put in a finally block.

8
The try Statement
To handle an exception in a program, the line that throws
the exception is executed within a try block

A try block is followed by one or more catch clauses

Each catch clause has an associated exception type and


is called an exception handler

When an exception occurs, processing continues at the


first catch clause that matches the exception type

17

Exception Handling Mechanism


try Block

Statements that causes


an exception

Throws
exception
Object

catch Block

Statements that
handle the exception

9
Syntax of Exception Handling Code

try {
// statements
}
catch( ExceptionType e)
{
// statements to process exception
}
..
..

Example:
class Exc2 {
public static void main(String args[]) {
int d, a;
try { // monitor a block of code,
d = 0;
a = 42 / d;
System.out.println{"This will not be printed.");
}
catch {ArithmeticException e) { // catch divide-by-zero error
System.out.printIn("Division by zero.");
}
System.out.println{"After catch statement.");
}
}
Output:
Division by zero.
After catch statement.

10
Finding a Sum of Integer Values Passed as
Command Line Parameters
// ComLineSum.java: adding command line parameters
class ComLineSum
{
public static void main(String args[])
{
int InvalidCount = 0;
int number, sum = 0;

for( int i = 0; i < args.length; i++)


{
try {
number = Integer.parseInt(args[i]);
}

catch(NumberFormatException e)
{
InvalidCount++;
System.out.println("Invalid Number: "+args[i]);
continue;//skip the remaining part of loop
}

sum += number;
}
System.out.println("Number of Invalid Arguments =
"+InvalidCount);
System.out.println("Number of Valid Arguments =
"+(args.length-InvalidCount));
System.out.println("Sum of Valid Arguments = "+sum);
}
}

11
C:\>java ComLineSum 3 4 12
Number of Invalid Arguments = 0
Number of Valid Arguments = 3
Sum of Valid Arguments = 19

C:\>java ComLineSum 3 4 a
Invalid Number: a
Number of Invalid Arguments = 1
Number of Valid Arguments = 2
Sum of Valid Arguments = 7

C:\>java ComLineSum 3 abc {}


Invalid Number: abc
Invalid Number: {}
Number of Invalid Arguments = 2
Number of Valid Arguments = 1
Sum of Valid Arguments = 3

Multiple Catch Statements


If a try block is likely to raise more than one type of exceptions, then
multiple catch blocks can be defined as follows:

try {
// statements
}
catch( ExceptionType1 e)
{
// statements to process exception 1
}
..
..
catch( ExceptionTypeN e)
{
// statements to process exception N
}

12
Example:

// Demonstrate multiple catch statements,


class MultiCatch {
public static void main(String args[ ]) {
try {
int a = args.length;
System.out.println("a = " + a);
int b = 42 / a;
int c[ ] = { 1 };
c[42] = 99;
}
catch(ArithmeticException e) {
System.out.println("Divide by 0: " + e);
}
catch(ArrayIndexOutOfBoundsException e) {
System.out.println( "Array index oob: " + e);
}
System.out.println{"After try/catch blocks.");
}
}

Output
C:\>java MultiCatch
a = 0
Divide by 0: java.lang.ArithmeticException: / by zero
After try/catch blocks.

C:\>java MultiCatch TestArg


a = 1
Array index oob: java.lang-ArraylndexOutOfBoundsException
After try/catch blocks.

13
14

Vous aimerez peut-être aussi