Exception Handling in Java
Objectives
• Introduction
• What exceptions are for
• Catching & Throwing exceptions
• Exception Specifications
• Standard Java Exceptions
• Exceptions and Polymorphism
• The finally clause
• Resource Management
• Uncaught Exceptions
Introduction
• Due to design errors or coding errors, our
programs may fail in unexpected ways during
execution. An exception is a condition that is
caused by run time error in the program. The
purpose of the exception handling mechanism
is to provide a means to detect and report an
“ecxceptional circumstances” .
Error
• An error may produce an incorrect output or
may terminate the execution of the program
abruptly or even may cause the system to
crash. So it is our responsibility to detect and
manage the error properly.
Types of error
• Runtime Errors: occur while the program is
running if the environment detects an
operation that is impossible to carry out.
• Logic Errors: occur when a program doesn't
perform the way it was intended
• Syntax Errors: Arise because the rules of the
language have not been followed. They are
detected by the compiler.
Errors in Java Program
There are basically three types of errors in java
program:
• Compile-time errors
• Run-time errors
• Logical errors
Compile-time errors
These are the syntactical errors found in the code, due to which a
program fails to compile.
For example, forgetting a semicolon at the end of a java statement
,or writing a statement without a proper syntax will result in
compile-time error.
//compile time error OUTPUT:
class err C:\>javac Err.java
{ Err.java:6: ‘;’ expected
public static void main(String args[ ])
{ Err.java:7: ‘;’ expected
System.out.println(“Hello”) System.out.println(“Where is error”)
System.out.println(“Where is error”)
}
}
In this program ,we are not writing a semicolon at the end of the statements.This will be detected by the
java compiler. Detecting and correcting compile-time errors is easy as the java compiler displays the list of
errors with the line numbers along with their description.
Run-time errors
These errors represent inefficiency of the computer system to execute a particular
statement.
For example, insufficient memory to store something or inability of the microprocessor
to execute some statement come under run-time error
//Run-time error OUTPUT:
class err C:\>javac Error.java
{ C:\>java Err
Exception in thread “main”
public static void main( ) java.lang.NoSuchMethodError:main
{
System.out.println(“Hello”);
System.out.println(“Where is error”);
}
}
Run-time errors are not detected by the java compiler. They are detected by the
JVM, only at run-time.
What happens if main( ) method is written without String args[ ]?
The code compiles but JVM cannot run it, as it cannot see the main( ) method
with String args[ ]
Example of Run Time error
Class Error
{
public static void main(String args[])
{
int a=10;
int b=5;
int c=5;
int x=a/(b+c);
System.out.println("x=" +x);
int y=a/(b-c); // Errorr division by zero
System.out.println("y=" +y);
}
}
Logical errors
These errors are flaws in the logic of the program.The programmer might be using wrong
formula or the design of the program itself is wrong.
Logical errors are not detected either by java compiler or JVM.The Programmer is solely
responsible for them.
//Logical error
class Err
{
public static void main(String args[ ] )
{
double salary=5000.00;
sal=sal*15/100; //wrong use :sal+=sal*15/100;
System.out.println(“Increment salary=”+sal);
}
} OUTPUT:
Incremented salary=750.0
By comparing the output of a program with manually calculated results, a
programmer can guess the presence of a logical error.
Errors and Error Handling
• Some typical causes of errors:
– Memory errors (i.e. memory incorrectly allocated,
memory leaks, “null pointer”)
– File system errors (i.e. disk is full, disk has been
removed)
– Network errors (i.e. network is down, URL does
not exist)
– Calculation errors (i.e. divide by 0)
Errors and Error Handling
• More typical causes of errors:
– Array errors (i.e. accessing element –1)
– Conversion errors (i.e. convert ‘q’ to a number)
– Can you think of some others?
Errors and Error Handling
• Exceptions – a better error handling
– Exceptions are a mechanism that provides the
best of both worlds.
– Exceptions act similar to method return flags in
that any method may raise and exception should it
encounter an error.
– Exceptions act like global error methods in that
the exception mechanism is built into Java;
exceptions are handled at many levels in a
program, locally and/or globally.
Exception
Exceptions can be checked and unchecked
The exception that are checked at compile time by the java compiler are
called checked exceptions.
The exceptions that are checked by the JVM are called unchecked exception.
• Unchecked exceptions and errors are considered as unrecoverable and the
programmer cannot do anything when they occur.
• The programmer can write a java program with unchecked exceptions and
errors and can compile the program.
Exception
What is Throwable?
Throwable is a class that represents all errors and exceptions which may
occur in java
Which is the super class of all exceptions?
Exception is the superclass of all exceptions in Java
What is the difference between an exception and an error?
An exception is an error which can be handled. It means when an exception
happens, the programmer can do something to avoid any harm. But an error
is an error which can not be handled, it happens and the programmer cannot
do any thing
What is an Exception?
An exception is an unwanted or unexpected event, which
occurs during the execution of a program i.e at run time,
that disrupts the normal flow of the program’s
instructions.
Error vs Exception
Error: An Error indicates serious problem that a
reasonable application should not try to catch.
Exception: Exception indicates conditions that a
reasonable application might try to catch.
Exception Hierarchy
All exception and errors types are sub classes of class Throwable, which is
base class of hierarchy.One branch is headed by Exception. This class is
used for exceptional conditions that user programs should catch.
NullPointerException is an example of such an exception.Another
branch,Error are used by the Java run-time system(JVM) to indicate errors
having to do with the run-time environment itself(JRE). StackOverflowError is
an example of such an error.
How JVM handle an Exception?
Default Exception Handling : Whenever inside a method, if an exception has occurred, the
method creates an Object known as Exception Object and hands it off to the run-time
system(JVM). The exception object contains name and description of the exception, and
current state of the program where exception has occurred. Creating the Exception Object and
handling it to the run-time system is called throwing an Exception.There might be the list of the
methods that had been called to get to the method where exception was occurred. This
ordered list of the methods is called Call Stack.Now the following procedure will happen.
•The run-time system searches the call stack to find the method that contains block of code
that can handle the occurred exception. The block of the code is called Exception handler.
•The run-time system starts searching from the method in which exception occurred, proceeds
through call stack in the reverse order in which methods were called.
•If it finds appropriate handler then it passes the occurred exception to it. Appropriate handler
means the type of the exception object thrown matches the type of the exception object it can
handle.
•If run-time system searches all the methods on call stack and couldn’t have found the
appropriate handler then run-time system handover the Exception Object to default exception
handler , which is part of run-time system. This handler prints the exception information in the
following format and terminates program abnormally.Exception in thread "xxx" Name of
Exception : Description ... ...... .. // Call Stack
Exceptions
• How do you handle exceptions?
– To handle the exception, you write a “try-catch”
block. To pass the exception “up the chain”, you
declare a throws clause in your method or class
declaration.
– If the method contains code that may cause a
checked exception, you MUST handle the
exception OR pass the exception to the parent
class (remember, every class has Object as the
ultimate parent)
Coding Exceptions
• Coding Exceptions
• Try-Catch Mechanism
– Wherever your code may trigger an exception, the
normal code logic is placed inside a block of code
starting with the “try” keyword:
– After the try block, the code to handle the
exception should it arise is placed in a block of
code starting with the “catch” keyword.
Standard Java Exceptions
Throwable
Exception Error
Runtime
IO Exception
Exception
Catching Exceptions
• Wrap code to be checked in a try-block
– checking occurs all the way down the execution
stack
• try-blocks can be nested
– control resumes at most enclosed matching
handler
Coding Exceptions
• Example
– try {
… normal program code
}
catch(Exception e) {
… exception handling code
}
Coding Exceptions
• Types of Exceptions
– Examples:
• public void myMethod throws Exception {
• public void myMethod throws IOException {
• try { … }
catch (Exception e) { … }
• try { … }
catch (IOException ioe) { … }
Code Examples
• 1. Demonstration of an unchecked exception
(NullPointerException)
• 2. Demonstration of checked exceptions:
– Passing a DivideByZeroException
– Handling a DivideByZeroException
Example
class error2
{
public static void main(String arg[])
{
int a=10;
int b=5;
int c=5;
int x,y;
try
{
x=a/(b-c);
}
catch(ArithmeticException e)
{
System.out.println(“Division by Zero”);
}
Y=a/(b-c);
System.out.println(“y=“+y);
}
}
In the previous program we cannot see the
value of x just because of the error in the
value of y, that is division by zero but when we
use the try and catch blocks in exception
handling then we can see the value of y which
is correct and our program will display an
error message shown in the try block.
conclusion
– Exceptions are a powerful error handling
mechanism.
– Exceptions in Java are built into the language.
– Exceptions can be handled by the programmer
(try-catch), or handled by the Java environment
(throws).
– Exception handling can only hide the errors.
– It cannot correct the errors.