Unit 4
Unit 4
Semester-4
R.C.Technical Institute
Unit – 4
Exception Handling and Multithreading
Exception Handling
●
Definition:
Exception is an abnormal condition. In java, exception is an event that disrupts the
normal flow of the program. It is an object which is thrown at runtime.
●
What is exception handling?
The exception handling in java is one of the powerful mechanisms to handle the
runtime errors so that normal flow of the application can be maintained.
●
The core advantage of exception handling is to maintain the normal flow of the
application.
Exception Handling Hierarchy
Types of Exception
●
There are mainly two types of exceptions: checked and
unchecked, where error is considered as unchecked exception.
The sun microsystem says there are three types of exceptions:
●
Checked Exception
●
Unchecked Exception
●
Error
Types of Exception
●
Checked Exception:
The classes that extend Throwable class except RuntimeException and Error are
known as checked exceptions. Checked exceptions are checked at compile-time.
e.g.IOException, SQLException etc
●
Unchecked Exception:
The classes that extend RuntimeException are known as unchecked exceptions.
Unchecked exceptions are not checked at compile-time rather they are checked at
runtime. e.g. ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException etc.
●
Error
Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, etc.
Some scenarios where exceptions may occur
ArithmeticException
●
If we divide any number by zero, there occurs an
ArithmeticException. int a=50/0;//ArithmeticException
NullPointerException
●
If we have null value in any variable, performing any operation by the variable occurs an
NullPointerException. String s=null;
System.out.println(s.length());//NullPointerException
NumberFormatException
●
The wrong formatting of any value, may occur NumberFormatException. Suppose I have a string variable
that have characters, converting this variable into digit will occur NumberFormatException.
String s="abc";
int i=Integer.parseInt(s);//NumberFormatException
ArrayIndexOutOfBoundsException
●
If you are inserting any value in the wrong index, it would result ArrayIndexOutOfBoundsException as
shown below: int a[]=new int[5];
a[10]=50; //ArrayIndexOutOfBoundsException
There are 5 keywords used in java exception handling.
●
try
●
catch
●
finally
●
throw
●
throws
Java try block
• 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.
• Syntax of java try-catch
try{
//code that may throw exception
}
catch(Exception_class_Name ref)
{
//code to catch exception
}
●
Syntax of try-finally block
try{
//code that may throw exception
}finally{}
Java catch block
●
Java catch block is used to handle the Exception.
●
It must be used after the try block only.
●
You can use multiple catch block with a single try.
●
At a time only one Exception is occurred and at a time only one
catch block 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.
Java finally block
●
Java finally block is a block that is used to execute important
code such as closing connection, stream etc.
●
Java finally block is always executed whether exception is
handled or not.
●
Java finally block follows try or catch block.
●
If you don't handle exception, before terminating the
program, JVM executes finally block(if any).
●
Finally block in java can be used to put "cleanup" code such
as closing a file, closing connection etc.
Java finally block
Java finally block
●
For each try block there can be zero or more catch blocks, but
only one finally block.
●
The finally block will not be executed if program exits. (either
by calling System.exit() or by causing a fatal error that causes
the process to abort).
Java throw keyword
●
The Java throw keyword is used to explicitly throw an
exception.
●
We can throw either checked or unchecked exception in
java by throw keyword.
●
The throw keyword is mainly used to throw custom
exception.
●
The syntax of java throw keyword is given below.
throw exception;
Java throws keyword
●
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 for the programmer to provide the exception handling code so
that normal flow can be maintained.
●
Exception Handling is mainly used to handle the checked
exceptions.
●
If there occurs any unchecked exception such as
NullPointerException, it is programmers fault that he is not
performing check up before the code being used.
●
Syntax of java throws
return_type method_name() throws exception_class_name{
//method code
}
●
If you are calling a method that declares an exception, you must
either caught or declare the exception.
●
There are two cases:
●
Case1: You caught the exception i.e. handle the
exception using try/catch.
●
Case2: You declare the exception i.e. specifying throws with
the method.
Difference between throw and throws
You cannot throw multiple exceptions. You can declare multiple exceptions.
Java Custom Exception
●
If you are creating your own Exception that is known as
custom exception or user-defined exception.
●
Java custom exceptions are used to customize the
exception according to user need.
●
By the help of custom exception, you can have your own
exception and message.
Java Programs on try and catch
Output:
java.lang.ArithmeticException: / by zero
rest of the code
Java Programs on multiple try and catch
try{
int a[]=new int[5];
a[5]=30/0;
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{
System.out.println("Parent Exception occurs");
}
System.out.println("rest of the code");
}
}
class Excep6{
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);
}
try{
int a[]=new int[5];
a[5]=4;
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e);
}
System.out.println("other statement”);
}catch(Exception e){System.out.println("handeled");}
System.out.println("normal flow..");
} }
Java Program on try catch and finally
if(age<18)
{
throw new ArithmeticException("not valid");
}
else
{
System.out.println("welcome to vote");
}
}
public static void main(String args[])
{
validate(13);
System.out.println("rest of the code...");
}
Output:
import java.io.IOException;
class Testthrows1{
void m()throws IOException
{
try{
throw new IOException("device error");//checked exception
}
catch(Exception e)
{
System.out.println("exception handled");}
}
}
public static void main(String args[])
{
Testthrows1 obj=new Testthrows1();
obj.m();
System.out.println("normal flow...");
}
}
Output:
exception handled
normal flow...
// Custom Exception Class
Java Program on custom exception
if (b == 0)
{
throw new MyException("Cannot divide by zero");
}
else {
c = a / b;
System.out.println(c);
}
}
catch (MyException e)
{
System.out.println("Caught: " + e.getMessage());
} }}
●
Multithreading in java is a process of executing multiple threads
simultaneously.
●
Thread is basically a lightweight sub-process, a smallest unit of
processing. Multiprocessing and multithreading, both are used to
achieve multitasking.
●
But we use multithreading than multiprocessing because threads
share a common memory area.
●
They don't allocate separate memory area so saves memory, and
context-switching between the threads takes less time than
process.
●
Java Multithreading is mostly used in games, animation etc.
Advantages of Java Multithreading
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.
How to create thread
●
There are two ways to create a thread:
●
By extending Thread class
●
By implementing Runnable interface.
●
Thread class:
●
Thread class provide constructors and methods to create and perform operations on a thread.
●
Thread class extends Object class and implements Runnable interface.
●
Commonly used Constructors of Thread class:
Thread()
Thread(String name)
Thread(Runnable r)
Thread(Runnable r,String name)
Commonly used methods of Thread class:
●
public void run(): is used to perform action for a 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 (temporarily cease execution) for the specified number of milliseconds.
●
public int getPriority(): returns the priority of the thread.
●
public int setPriority(int priority): changes the priority of the thread.
●
public String getName(): returns the name of the thread.
●
public void setName(String name): changes the name of the thread.
●
public Thread currentThread(): returns the reference of currently executing
thread.
●
public int getId(): returns the id of the thread.
Commonly used methods of Thread class:
●
public void yield(): causes the currently executing thread object to
temporarily pause and allow other threads to execute.
●
public void suspend(): is used to suspend the thread.
●
public void resume(): is used to resume the suspended thread.
●
public void stop(): is used to stop the thread.
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().
public void run(): is used to perform action for a thread.
● Starting a thread:
● start() method of Thread class is used to start a newly created thread. It
performs following tasks:
– A new thread starts
– The thread moves from New state to the Runnable state.
– When the thread gets a chance to execute, its target run() method will run.
Priority of a Thread (Thread Priority)
● Each thread has a priority.
● Priorities are represented by a number between 1 and 10.
● In most cases, thread schedular schedules the threads according to their
priority.
● But it is not guaranteed because it depends on JVM specification that
which scheduling it chooses.
● 3 constants defined in Thread class:
● public static int MIN_PRIORITY
● public static int NORM_PRIORITY
● public static int MAX_PRIORITY
● Default priority of a thread is 5 (NORM_PRIORITY).
● The value of MIN_PRIORITY is 1 and the value of MAX_PRIORITY is 10.
Program of Multithreading using Runnable Interface
Java Synchronization is better option where we want to allow only one thread to access the shared resource.
class Table{
void printTable(int n){//method not synchronized
for(int i=1;i<=5;i++){
System.out.println(n*i);
try{
Thread.sleep(400);
}
catch(Exception e)
{System.out.println(e);}
} } }
Program Cont...
class TestSynchronization1{
public static void main(String args[]){
Table obj = new Table();//only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start();
}
}
Program Cont...
Output:5
100
10
200
15
300
20
400
25
500
Java synchronized method
}
Program cont..
Output: 5
10
15
20
25
100
200
300
400
500
Synchronized Block in Java
• Synchronized block can be used to perform synchronization on any specific resource of the method.
• Suppose you have 50 lines of code in your method, but you want to synchronize only 5 lines, you can use synchronized
block.
• If you put all the codes of the method in the synchronized block, it will work same as the synchronized method.
}
class MyThread2 extends Thread{
Table t;
MyThread2(Table t){
this.t=t;
}
public void run(){
t.printTable(100);
}
}
Output:5
10
15
20
25
100
200
300
400
500
Exception Handling in Thread