Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
XI. Exception Handling
Objectives
In this section, we are going to study a technique used in Java to handle unusual conditions that
interrupt the normal operation of the program.
At the end of the chapter, the student should be able to:
• Define exceptions
• Handle exceptions using a simple try‐catch‐finally block
Exceptions
An exception is a java event resulting from erroneous situation which disrupts the normal
program flow of instructions. Java has different exceptions, the I/O exceptions, run‐time‐
exceptions and checked exceptions. Run‐time‐exceptions include dividing by zero among other
under arithmetic exceptions. A checked exception is when the compiler checks each method
during compilation, to ensure that each method has a handler.
Exception Handling
Exception Handling is a general concept of planning for possible exceptions by directing the
program to deal with them without terminating prematurely.
Exception handling should be applicable to the following scenario:
to process exceptional situations where a method is unable to complete its task for
reasons it cannot control
to process exceptions from program components that are not geared in handling those
exceptions directly
Try‐Catch
We use try‐catch statement to handle exceptions in Java. Inside a try statement we include the
statements that might cause the exceptions. The try statement must be followed by a catch
statement. A catch statement handles caught exceptions thrown by called methods.
Training-workshop on Object-oriented Programming using Java
80 | P a g e
General syntax:
try {
statement/s that might generate an exceptions;
}
catch(ExceptionName identifier)
{
statement/s that handle an exception;
}
Example:
try
{
Sales=integer.parseInt(answer);
}
catch(NumberFormatException e);
{
System.out,println(“Input not in format!”);
}
Throw
When the throw statement was executed it indicates that an exception happened thus, method
was not performed successfully. To throw an exception it always accompanied by the throw
statement and it requires a single argument and that is the throwable object.
try
{
sales=integer.parseInt(answer);
}
catch(NumberFormatException e);
if(sales<=0) throw new NumberFormatException( );
{
System.out,println(“Input not in format!”);
}
Finally Statement
The try‐catch statement can be optionally be followed by a finally statement, which is put after
the catch statement. This contains statements to perform any clean up that might be necessary
after executing the try‐catch statements.
try
{
sales=integer.parseInt(answer);
}
catch(NumberFormatException e);
if(sales<=0) throw new NumberFormatException( );
{