CS3391 Oops Unit 3
CS3391 Oops Unit 3
CS3391 Oops Unit 3
PROGRAMMING
UNIT 3
Exception Handling and Multithreading
by
S.Sakkaravarthi, AP/IT
Ramco Institute of Technology, Rajapalayam
UNIT 3-TOPICS
1.Exception
2.Errors
Exception
The compiler checks for checked exception The compiler does not check for
unchecked exception
If checked exceptions are not handled, then If unchecked exceptions are not handled,
get compile time error then get run time error
Checked Exceptions are direct subclasses of UnChecked Exceptions are subclasses of
Exception but do not inherit Runtime the Runtime Exception class
Exception class
Example: IOException, Example: ArithmeticException,
ClassNotFoundException, SQLException NullPointerException,
ArrayIndexOutofBoundxception
Java Exception Keywords
try
{
//code that may throw an exception
}
catch(ExceptionClassName ref)
{
//code that may throw an exception
}
try-finally block-syntax
try
{
//code that may throw an exception
}
finally
{
//code
}
finally block
finally block is a block used to execute important code such
closing the database connection.
Java code within the finally block is always executed
whether an exception is handled or not. Therefore, it
contains all the necessary statements that need to be printed
regardless of the exception occurs or not.
The finally block follows the try-catch block.
Multiple catch clauses
A try block can be followed by one or more catch blocks.
Each catch block must contain a different exception handler. Hence multi-
catch block is used to perform different tasks at the occurrence of different
exceptions.
At a time only one exception occurs and at a time only one catch block is
executed.
All catch blocks must be ordered from most specific to more general
i.e., catch for Arithmetic Exception must come before catch for Exception.
Multiple Catch Block
class Muticatchdemo
{
public static void main(String args[])
{
try
{
int a[]=new int[5];
a[5]=30/0;
}
catch(ArithmeticException e)
{
System.out.println(“Arithmetic exception occurs:”+e);
}
Multiple Catch Block
catch(ArrayIndexOutofBoundsException e)
{
System.out.println(“Array index out of bounds exception occurs:”+e);
}
catch(Exception e)
{
System.out.println(e);
}
System.out.println(“rest of code executes”);
}
}
Multithreading Programming
Multitasking is a process of executing multiple tasks
simultaneously. The concept of multitasking is to utilize the
CPU at its Maximum. Multitasking can be achieved in two
ways
Process-based Multitasking (Multiprocessing)