Exception Handling
Exception Handling
Exceptions
An exception is an object that describes an unusual or erroneous situation.
Exceptions are thrown by a program and may be caught and handled by another
part of the program.
(Dictionary Meaning: Exception is an abnormal condition).
In Java, an exception is an event that disrupts the normal flow of
the program. It is an object which is thrown at runtime.
Advantage of Exception Handling
The core advantage of exception handling is to maintain the
normal flow of the application. An exception normally disrupts
the normal flow of the application; that is why we need to handle
exceptions.
Exception Hierarchy
Errors:
Errors are fairly rare and usually fatal. They are
caused by bugs in the Java VM, or by the
program running out of memory or other
resources.
Errors are usually not handled by programs.
Exceptions:
Exceptions can be caused by bugs in the
program or improper data supplied to the
program
Exceptions should be handled, or caught
An exception is either checked or unchecked
Checked exceptions must be caught or declared
as thrown.
Attack of the Exception
Output:
Exception in thread "main“ java.lang.ArrayIndexOutOfBoundsException: 2
at ExceptionExample.main(ExceptionExample.java:4)
Exception Message Details
Exception message format:
[exception class]: [additional description of exception]
at [class].[method]([file]:[line number])
Example:
java.lang.ArrayIndexOutOfBoundsException: 2
at ExceptionExample.main(ExceptionExample.java:4)
What exception class? ArrayIndexOutOfBoundsException
Which array index is out of bounds? 2
What method throws the exception? main
What file contains the method? ExceptionExample.java
What line of the file throws the exception? 4
Classifying Java Exceptions
1) Checked Exception
The classes that directly inherit the Throwable class
9
Checked Exceptions
Usually occur because of errors, programmer cannot control it.
examples: hardware failures, unreadable files
They are less frequent, and they cannot be ignored by the programmer . . .
Every method must catch (handle) checked exceptions or specify that it may throw
them
Specify with the throws keyword
Checked and Unchecked Exceptions
Checked Exception Unchecked Exception
ArrayIndexOutofBounds FileNotFoundException
NullPointerException MalformedURLException
IllegalArgumentException SocketException
etc. etc.
}
}
Example of Exception
public class Exception1 {
public class Exception1 { public static void main (String []
public static void main args) {
(String [] args) { int a[]={10,20,30,0,50,60};
for(int i=0;i<a.length;i++)
int a[]={10,20,30,0,50,60}; {
for(int i=0;i<a.length;i++) try
{
{ float y=60/a[i];
float y=60/a[i]; System.out.println(y);
}
System.out.println(y);
catch(Exception e)
{
}
System.out.println("invalid
} division");
}
}
class Demo
{
static void throwOne() throws IllegalAccessException {
System.out.println("Inside throwOne.");
throw new IllegalAccessException("demo");
}
public static void main(String args[]) {
try {
throwOne();
}
catch (IllegalAccessException e) {
System.out.println("Caught " + e);
}
} }
throws Clause
Example 3:
class Demo
{
static void throwOne() throws IllegalAccessException {
System.out.println("Inside throwOne.");
throw new IllegalAccessException("demo");
}
public static void main(String args[]) {
try {
throwOne();
}
catch (IllegalAccessException e) {
System.out.println("Caught " + e);
} Output:
} inside throwOne
} caught
java.lang.IllegalAccessExcepti
on: demo
finally
If the try block is executed, then the finally block is guaranteed to be
executed, regardless of whether any catch block was executed.
Since the finally block is always executed before control transfers to its
final destination, the finally block can be used to specify any clean-up code
(e.g., to free resources such as files and net connections).
The finally block will execute whether or not an exception is thrown.
finally
Example 3:
class Demo
{
static void throwOne() throws IllegalAccessException {
System.out.println("Inside throwOne.");
throw new IllegalAccessException("demo");
}
public static void main(String args[]) {
try {
throwOne();
}
catch (IllegalAccessException e) {
System.out.println("Caught " + e);
}
finally{
System.out.println(" finally executed");
}
} }
finally
Example 3:
class Demo
{
static void throwOne() throws IllegalAccessException {
System.out.println("Inside throwOne.");
throw new IllegalAccessException("demo");
}
public static void main(String args[]) {
try {
throwOne();
}
catch (IllegalAccessException e) {
System.out.println("Caught " + e);
}
finally{
System.out.println(" finally executed"); Output:
} inside throwOne
}
} caught
java.lang.IllegalAccessEx
ception: demo
finally executed
Built-In Exceptions
Java defines several exception classes.
The most general of these exceptions are subclasses of the standard type
RuntimeException.
As previously explained, these exceptions need not be included in any
method’s throws list.
These are called unchecked exceptions because the compiler does not
check to see if a method handles or throws these exceptions.
The checked exceptions must be included in a method’s throws list if that
method can generate one of these exceptions and does not handle it itself.
In addition to the exceptions in java.lang, Java defines several more that
relate to its other standard packages.
Built-In Exceptions
Throwable class:
The Throwable class is the superclass of all errors and exceptions in the
Java language.
Only objects that are instances of this class (or one of its subclasses) are
thrown by the Java Virtual Machine or can be thrown by the Java throw
statement.
Similarly, only this class or one of its subclasses can be the argument type in
a catch clause.
By convention, class Throwable and its subclasses have two constructors,
one that takes no arguments and one that takes a String argument that can be
used to produce a detail message.
Java’s Unchecked RuntimeException Subclasses
Defined in java.lang
Java’s Checked Exceptions Defined in java.lang
Creating Your Own Exception
Although Java’s built-in exceptions handle most common errors.
However, you will probably want to create your own exception types to
handle situations specific to your applications.
To do just define a subclass of Exception.
The Exception class does not define any methods of its own. It does, of
course, inherit those methods provided by Throwable.
Exception defines four public constructors.
Creating Your Own Exception
class MyException extends Exception {
private int detail;
MyException(int a) {
detail = a;
}
public String toString() {
return "MyException[" + detail + "]";
}
}
class ExceptionDemo {
static void compute(int a) throws MyException {
System.out.println("Called compute(" + a + ")");
if(a > 10)
throw new MyException(a);
System.out.println("Normal exit");
}
public static void main(String args[]) {
try {
compute(1);
compute(20);
} catch (MyException e) { Called compute(1)
System.out.println("Caught " + e); Normal exit
} Called compute(20)
} Caught MyException[20]
}
Example 2 (Invalid Age )
// class representing custom exception // throw an object of user defined exception
throw new InvalidAgeException("age is not va
class InvalidAgeException extends Exception
lid to vote");
{ }
public InvalidAgeException (String str) else {
System.out.println("welcome to vote");
{ } }
// calling the constructor of parent Exception
super(str); // main method
public static void main(String args[]) {
} try
} {
// class that uses custom exception InvalidAgeEx // calling the method
validate(13);
ception
}
public class TestCustomException1 catch (InvalidAgeException ex)
{ {
System.out.println("Caught the exception");
// method to check the age
static void validate (int age) throws InvalidAg
eException{ // printing the message from InvalidAgeExcep
tion object
if(age < 18){
System.out.println("Exception occured: " + e
x);
}