22ADT32 - Java Programming
UNIT 3 EXCEPTION HANDLING AND
MULTITHREADING
Exception Handling basics – Multiple catch Clauses –
Nested try Statements – Java’s Built-in Exceptions – User
defined Exception. Multithreaded Programming: Java
Thread Model–Creating a Thread and Multiple Threads –
Priorities – Synchronization – Inter Thread Communication
- Suspending –Resuming, and Stopping Threads –
Multithreading. Wrappers – Auto boxing
Exception Handling basics
John is in hospital
He found these pictures are hanged on the walls of every floor corridors.
What are these pictures?
It shows how you have to think in advance about possibilities of mishaps that can occur
and what are the preventive measures that can be taken.
Types of Errors
Exception Hierarchy
All exception types are subclass of built in class throwable.
Exceptions can be handled where as errors cannot be handled by user
Exception Handling basics – contd..
An exception is an event that occurs during the execution of a program that disrupts the
normal flow of instructions. It is an object which is thrown at runtime.
Similarly whenever we are writing a program, we have to visualize the challenges that
can disrupt the normal flow of execution of the code.
The ability of a program to intercept run-time errors, take corrective measures and
continue execution is referred to as exception handling
It is responsibility of the programmer to ensure that the program are error free in all
aspects.
Exception Handling basics – contd..
Situations when exception can occur
Attempting to access a file that does not exist
Inserting an element into an array at a position that is not in its bounds
Performing some mathematical operation that is not permitted
Giving size of array as negative
Whenever exception condition arises, an object representing that exception is created
and thrown in the method that caused the error.
The exception is caught and processed by the corresponding method defined for
handling it.
Either you can handle the exception or ignore it.
If exception is not handled manually then Java run-time system handles exception and
the program terminates abnormally or abruptly without worrying about other
statements.
However handling exceptions will allow to fix it and prevent the program from
terminating abnormally.
Exception Handling basics – contd..
Exceptions handling – managed by 5 keywords
try – write the code that you want to monitor
catch – handle the exception
throw - throw an exception
throws – any exception that is thrown out of a method
finally – code that must be executed after try block completes
Keyword Description
try The "try" keyword is used to specify a block where we should place an exception code. It means we
can't use try block alone. The try block must be followed by either catch or finally.
catch The "catch" block is used to handle the exception. It must be preceded by try block which means we
can't use catch block alone. It can be followed by finally block later.
finally The "finally" block is used to execute the necessary code of the program. It is executed whether an
exception is handled or not.
throw The "throw" keyword is used to throw an exception.
throws The "throws" keyword is used to declare exceptions. It is always used with method signature.
Uncaught exceptions in Java
class ExceptionDemo
{
public static void main(String args[])
{
int d=0;
int a=42/d;
[Link](a);
}
}
Output:
I:\Programs>javac [Link]
I:\Programs>java ExceptionDemo
Exception in thread "main" [Link]: / by zero
at [Link]([Link])
Explanation:
Will result in an runtime error. (i.e abnormal termination of program)
Exception Handling Syntax
try
{
//block of code to monitor for errors
}
catch(ExceptionType exOb)
{
//Exception handler for exception
}
//..
finally
{
//block of code to be executed after try block ends
}
Exception Handling Example
class ExceptionDemo }
{ finally
public static void main(String args[]) {
{ [Link]("Completed");
try }
{ }
int d=0; }
Output:
int a=42/d;
Divisor value is Zero, Unable to perform division
Completed
[Link](a);
}
catch(ArithmeticException e)
{
[Link]("Divisor value is Zero, Unable
to perform division");
Execution flow when an exception occurs
Execution flow when there is no exception VS exception occurs
Rules for try – catch – finally block
Statements that might generate an exception are placed in a try block.
Not all statements in the try block will execute; the execution is interrupted if an
exception occurs
For each try block there can be zero or more catch blocks, but only one finally block.
The try block is followed by
one or more catch blocks
or, if a try block has no catch block, then it must have the finally block
A catch block specifies the type of exception it can catch. It contains the code known
as exception handler
The catch blocks and finally block must always appear in conjunction with a try block.
Multiple catch clause
Multiple catch is used to handle
many different kind of exceptions catch(ExceptionType2 exOb2)
that may be generated while
running the program. {
i.e more than one catch clause in a //Exception handler for exception
single try block can be used. type 2
try }
{
//block of code to monitor for errors //….
} finally
catch(ExceptionType1 exOb1) {
{ //block of code to be executed after
try block ends
//Exception handler for exception
type 1 }
}
Multiple catch clause – Contd..
At a time only one Exception can occur and at a time only one catch
block is executed and others are bypassed. Then statements after try-
catch is executed.
All catch blocks must be ordered from most specific to most general i.e.
catch for ArithmeticException must come before catch for Exception.
Because Exception is super class of ArithmeticException. Exception class
can also catch Arithmetic exception.
Multiple catch clause – Example
class MultiplecatchDemo occurs");
{ }
public static void main(String args[]) catch(ArrayIndexOutOfBoundsException e)
{ {
try [Link]("Out of index exception
{ occurs");
int a[]= {1,2,0}; }
[Link]("Thank you");
[Link](a[0]);
[Link](a[1]/a[2]); }
[Link](a[3]); }
Output:
}
catch(ArithmeticException e) 1
{ Arithmetic Exception occurs
[Link]("Arithmetic Exception Thank you
Nested try statements
try block within a try block is known as nested try block.
Need for nested try
Sometimes a situation may arise where a part of a block may cause one
exception and the entire block itself may cause another exception. In
such cases, exception handlers have to be nested.
If an inner try statement does not have a matching catch statement for a
particular exception, the control is transferred to the next try statement’s
catch handlers that for a matching catch statement.
If none of the catch statement match, then the Java run-time system will
handle the exception.
Nested try statements
try }
{ catch(ExceptionType2 e2)
statement 1; {
statement 2; }
try
{
statement 1;
statement 2;
}
catch(ExceptionType1 e1)
{……
}
Nested try statements
class ExceptionDemo }
{ [Link](a[3]);
public static void main(String args[]) }
{ catch(ArrayIndexOutOfBoundsException e)
try {
{ [Link]("Index out of bound exception
occurs");
int a[]= {1,2,0};
}
[Link](a[0]);
[Link]("Thank you");
try //inner try
}
{
}
[Link](a[1]/a[2]);
Output:
}
1
catch(ArithmeticException e)
Divisor is zero, Arithmetic Exception occurs
{
Index out of bound exception occurs
[Link](“Divisor is zero, Arithmetic
Exception occurs"); Thank you
Till now we have seen only Throw clause
catching the exceptions that are thrown by
Java run time system.
An exception can be thrown explicitly
Using the throw statement
Using the throws statement
When throw statement is encountered:
It stops the execution of the subsequent statements
It transfers the control to the nearest catch block handling the type of exception
object thrown
If no such catch block exists, then the program terminates
Syntax: throw <exception reference>;
The Exception reference must be of type Throwable class or one of its subclasses.
Throw clause - Example
public class Demo catch (ArithmeticException e)
{ {
public static void main(String args[]) [Link]([Link]());
{ [Link]("Not a valid age");
int age=-3; }
try }
{ }
if(age<0) Output:
throw new ArithmeticException("Throwing"); //throw Throwing
clause Not a valid age
else
[Link]("welcome");
}
Throws clause
If a method is capable of raising an exception that it does not handle, the method must
specify that the exception have to be handled by the calling method.
This is done using the throws clause. The throws clause specify the types of exception
that a method might throw and signals the caller function to handle the exception.
Syntax: return_type method throws <exception reference>;
Throws clause - Example
public class Demo {
{ [Link](-3);
void validate(int age) throws ArithmeticException //throws }
clause catch (ArithmeticException e)
{ {
if(age < 0)
[Link]([Link]())
throw new ArithmeticException("throws"); // throw clause [Link]("Not a valid age
else }
[Link]("welcome");
}
} }
public static void main(String args[])
{
Output:
Demo d=new Demo(); throws
try Not a valid age
Rethrowing exceptions
Rethrowing exception - An exception can be rethrown in a catch block
using throw keyword, if catch block is unable to handle it.
Syntax:
catch(Exception e)
{
….
throw e;
}
Rethrowing exception - Example
public class Demo }
{ public static void main(String args[])
public int test(int n1, int n2) {
{ Demo d = new Demo();
try [Link]([Link](30, 0));
{ }
return n1/n2; }
} Output:
catch(ArithmeticException e) Exception in thread "main"
{ [Link]: / by
zero
throw e;
at [Link]([Link])
}
at [Link]([Link])
Finally- Example
Finally block will be executed both when the exception occurs and also if the
exception does not occurs also.
class ExceptionDemo {
{ [Link]("Divide by Zero Error");
public static void main(String args[]) }
{ finally
try {
{ [Link]("Completed");
int d=0; }
}
int a=42/d;
}
Output:
[Link](a);
Divide by Zero Error
} Completed
catch(ArithmeticException e)
Types of Exceptions
Built in Exceptions
Built in exceptions - that are already in [Link] package
2 types of built in exception
Checked- at compile-time, must be handled by user by try catch or throw
Unchecked Exceptions- at runtime, can be handled automatically
Sample unchecked Exception
Unchecked Exception - Example
class UncheckedException1
{
public static void main(String args[])
{
int num[] ={10,20,30,40,50,60};
[Link](num[7]);
}
}
Output:
Exception in thread "main" [Link]:
Index 7 out of bounds for length 6 at
[Link]([Link])
Sample checked Exception
Checked Exception - Example
class Simple }
{ catch (NoSuchMethodException e)
public void display() {
{ [Link]("Method is not
[Link]("Welcome"); found");
} }
} }
public class Demo }
{
public static void main(String[] args) Output:
{ Method is not found
try
{
Simple A = new Simple();
Class<?> clazz = [Link]();
[Link]("print");
User defined Exceptions
We can write our own exception class by extends the Exception class.
We can throw our own exception on a particular condition using the throw
keyword.
For creating a user-defined exception, we should have basic knowledge
of the try-catch block and throw keyword.
User defined Exceptions - example
class InvalidAgeException extends Exception {
{ throw new InvalidAgeException("Age cannot be
negative");
public InvalidAgeException(String message)
}
{
else
super(message);
{
}
[Link]("Welcome");
}
}
public class Demo
}catch (InvalidAgeException e)
{
{
public static void main(String[] args)
[Link]("Caught an exception\n" +
{
[Link]());
int age = -3;
} } }
try
Output:
{
Caught an exception
if (age < 0)
Age cannot be negative
A thread is a lightweight sub-process / independent units of a
process. Multithreaded Programming
It is the smallest unit of program that can run concurrently with
the other threads.
If there occurs exception in one thread, it doesn't affect other
threads.
Multitasking a process is overhead whereas multitasking threads
are easy.
Multithreading makes you to use the resources effectively.
Multithreaded programming
A thread is executed inside the process
Context switching is easy and less costly
There are multiple processes inside the OS, and
one process can have multiple threads.
Multithreading is a technique of executing more
than one thread, performing different tasks,
simultaneously.
For example, one thread is writing content on a
file at the same time another thread is
performing printing a document and another
Advantages of Multithreaded programming
Threads share the same address space and therefore can share both data and
code.
Context switching between threads is usually less expensive that between
processes.
Cost of thread communication is low than inter-process communication.
Different tasks can be performed concurrently.
Reduces the computation time.
Effective utilization of system resources.
Multitasking is achieved. (Single program performs two or more tasks