Exception Handling &: Multithreaded Programming
Exception Handling &: Multithreaded Programming
Multithreaded Programming
[16]
Errors [2M]
Errors are the wrongs that can make a program
go wrong.
Error may produce incorrect o/p or may
terminate the execution of program abruptly or
may cause system to crash.
Compile-Time:
Example:
Run-Time:
Errors [contd..]
Example:
Exception[4M]
Exception is a condition that is caused by run-
time error in a program.
In java, exception is an event that disrupts the
normal flow of the program.
It is an object which is thrown at runtime.
Exception Description
class or
ClassNotFoundException Class not
interface.
found.
IllegalAccessException
Access to a A
InstantiationException class is requested
denied. field does
not exist.
Attempt
NoSuchFieldException A requested
to create
an object method does
NoSuchMethodException of an not exist.
abstract
Exception [contd..]
Arithmetic error, such as
ArithmeticException
divide-by-zero.
ArrayIndexOutOfBoundsExc Array index is out-of-
eption bounds.
Assignment to an array
ArrayStoreException element of an incompatible
type.
Illegal argument used to
IllegalArgumentException
invoke a method.
Array created with a
NegativeArraySizeException negative size.
NullPointerException Invalid use of null reference.
Invalid conversion of a
NumberFormatException
string to a numeric format.
SecurityException Attempt to violate security.
Attempt to index outside the
StringIndexOutOfBounds
bounds of a string.
Exception Handling [4M]
Exception Handling is a mechanism to handle
runtime errors such as ClassNotFound, SQL, etc.
The core advantage of exception handling is to
maintain the normal flow of the application.
Exception Handling [contd..]
checked at compile-time.
Unchecked: The classes that
extend RuntimeException
There are 5 keywords are known as unchecked
used in java exception exceptions e.g.
handling: ArithmeticException,
try catch finally throw NullPointerException,
throws ArrayIndexOutOfBoundsE
xception etc. Unchecked
Two types: exceptions are not
Checked: The classes that checked at compile-time
extend Throwable class rather they are checked
except RuntimeException at runtime.
are known as checked
exceptions
e.g.IOException,
SQLException etc.
Checked exceptions are
Try-catch block [2M]
Java try block is used to enclose the code that
might throw an exception.
It must be used within the method.
Java try block must be followed by either catch
or finally block.
Java catch block is used to handle the
Exception. It must be used after the try block
only.
We can use multiple catch block with a single
try.
Syntax:
try{
//code that may throw
exception }catch(Exception_class
_Name ref)
{
//code that handles exception
}
Try-catch block [contd..]
Example:
public class Test{
public static void main(String args[]){
int data=50/0;
System.out.println("rest of the code...");
}
}
Using try-catch:
public class Test{
public static void main(String args[]){
try{
int data=50/0;
}
catch(ArithmeticException e){
System.out.println(e);
}
System.out.println("rest of the code...");
}}
Multiple catch block
To perform different tasks at the occurrence of
different Exceptions.
Example:
public class Test{
public static void main(String args[]){
try{
int a[]=new int[5];
a[5]=30/0;
}
catch(ArithmeticException e)
{ System.out.println("task1 is
completed");
}
catch(ArrayIndexOutOfBoundsException e)
{ System.out.println("task 2 completed");
}
System.out.println("rest of the code...");
}
}
Nested try block
The try block within a try block
Example:
class Test{
public static void main(String args[]){
try{
try{
System.out.println("going to divide");
int b =39/0;
}catch(ArithmeticException e){
System.out.println(e);
}
System.out.println("other statement");
}catch(Exception e){
System.out.println("handeled");
}
System.out.println("normal flow..");
}
}
Finally block [2M]
Java finally block is always executed whether
exception is handled or not.
Finally block in java can be used to put
"cleanup" code such as closing a file, closing
connection etc.
For each try block there can be zero or more
catch blocks, but only one finally block.
Example:
public class TestFinallyBlock2{
public static void main(String args[]){
try{
int data=25/0;
System.out.println(data);
}
catch(ArithmeticException e){System.out.println(e);}
finally{System.out.println("finally block executed");}
}
}
Throw statement [2M]
The Java throw keyword is used to explicitly
throw an exception.
Mainly used to throw custom exception.
Syntax: throw new Throwable’s subclass;
Example:
public class Test{
public static void main(String args[]){
int age = 13;
if(age<18)
throw new ArithmeticException("not valid");
else
System.out.println("welcome to vote");
System.out.println("rest of the code...");
}
}
User Defined Exception [4M]
class MyException extends Exception{
MyException(String str) {
super(str);
}}
class Test{
public static void main(String args[]){
String s1=“arkp”, s2=“aiktc”;
try{
if(s1.equals(s2))
throw new MyException("Custom");
else
System.out.println(“Strings Matched”) ;
}
catch(MyException exp){
System.out.println(exp) ;
}
}}
Programs [4M]
WAP to throw user defined exception “String
Mismatch Exception” if two strings are not
equal.
WAP to throw user defined exception as ‘invalid
age’ if age entered by user is less than 18.
WAP to input name and age of a person and
throw user-defined exception, if entered age is
negative.
WAP to raise user-defined exception if
username is less than 6 character and
password does not match.
Can we use exception as a debugger tool?
(pg: 240)
Throws statement [2M]
The Java throws keyword is used to declare an
exception.
It gives an information to the programmer that
there may occur an exception so it is better to
provide the exception handling code so that
normal flow can be maintained.
checked exception only.
Syntax:
return_type method_name() throws
exception_class_name {
//method code
}
x
E a
m s
p
l T
e e
: s
t
p {
u
b
l
i
c
c
l
a
s
Throws statement [2M]
Example:
import java.io.IOException;
class Test {
void m()throws IOException{
throw new IOException("device error"); }
void n()throws IOException{
m(); }
void p(){
try{
n();
}catch(Exception e){
System.out.println("exception handled"); } }
public static void main(String args[]){ Test
obj=new Test();
obj.p();
System.out.println("normal flow...");
}
}
Throws vs throw [4M]
No. throw throws
Throws
Java throw keyword is used
Java throws is used
) to explicitly throw an
keyword is with the
exception.
used to declare method
Checked exception cannot an exception. signatur
) be propagated using throw e.
only.
Checked
) Throw is followed by an exception Can
instance.
can be decla
) Throw is used within the propagated re
method.
with throws. multi
ple
) Cannot throw multiple exce
exceptions. Throws is ption
followed by s.
class.
Example
6) Example
Thread [2M]
background
Thread is basically a
lightweight process Adv.:
a smallest unit of processing
can perform many
Subpart of program operations together so
It comprises of thread ID, saves time.
program counter, register Threads are independent so
set it doesn't affect other
It shares code section and threads if exception occur in
data section belonging to a single thread.
same program
E.g: word processor may
have a thread for displaying
graphics, another for
responding to keystrokes,
and third for checking
spelling and grammar in
Lifecycle of Thread [4M]
1) New: The thread is in new state if you create
an instance of Thread class but before the
invocation of start() method.
2) Runnable: The thread is in runnable state
after invocation of start() method, but the
thread scheduler has not selected it to be the
running thread.
3) Running: The thread is in running state if the
thread scheduler has selected it.
4) Non-Runnable (Blocked): This is the state
when the thread is still alive, but is currently
not eligible to run.
5) Terminated: A thread is in terminated or
dead state when its run() method exits.
Lifecycle of Thread [contd..]
Lifecycle of Thread [4M]
There are two ways to create a thread:
By extending Thread class
By implementing Runnable interface.
Thread class:
Commonly used Constructors of Thread class:
Thread()
Thread(String name)
Thread(Runnable r)
Thread(Runnable r, String name)
Methods:
public void run(): to perform action for thread.
public void start(): starts the execution of the thread. JVM calls
the run() method on the thread.
public void sleep(long miliseconds): Causes the currently
executing thread to sleep for the specified milliseconds.
public int getPriority(): returns the priority of
the thread.
Lifecycle of Thread [4M]
public void sleep(long miliseconds): Causes the currently
executing thread to sleep for the specified milliseconds.
public int getPriority(): returns the priority of the thread.
public int setPriority(int priority): changes the priority of the
thread.
public boolean isAlive(): tests if the thread is alive.
public void yield(): causes the currently executing thread object
to temporarily pause and allow other threads to execute.
class Multi extends Thread{
public void run(){
System.out.println("thread is running...");
}
public static void main(String args[]){
Multi t1=new Multi(); t1.start();
}
}
Lifecycle of Thread [4M]
Runnable interface:
The Runnable interface should be implemented
by any class whose instances are intended to
be executed by a thread. Runnable interface
have only one method named run().
class Test implements Runnable{
public void run(){
System.out.println("thread is running...");
}
public static void main(String args[]){
Test m1=new Test();
Thread t1 =new Thread(m1);
t1.start();
}
}