0% found this document useful (0 votes)
38 views50 pages

Unit 4

The document provides an overview of Exception Handling and Multithreading in Java, explaining key concepts such as types of exceptions, the use of try-catch-finally blocks, and the creation and management of threads. It details the differences between checked and unchecked exceptions, the role of keywords like throw and throws, and the lifecycle of threads. Additionally, it includes Java code examples demonstrating exception handling and multithreading techniques.

Uploaded by

anshkathrecha13
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
38 views50 pages

Unit 4

The document provides an overview of Exception Handling and Multithreading in Java, explaining key concepts such as types of exceptions, the use of try-catch-finally blocks, and the creation and management of threads. It details the differences between checked and unchecked exceptions, the role of keywords like throw and throws, and the lifecycle of threads. Additionally, it includes Java code examples demonstrating exception handling and multithreading techniques.

Uploaded by

anshkathrecha13
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 50

Gujarat Technological University

Diploma Computer Engineering

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

Throw Keyword Throws Keyword


Java throw keyword is used to explicitly throw Java throws keyword is used to declare an
an exception. exception.

Checked exception cannot be propagated using Checked exception can be propagated


throw keyword. with throws keyword.
Throw is followed by an instance of exception Throws is followed by class.
class.
Throw is used within the method body. Throws is used with the method signature.

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

public class TryCatchExample {

public static void main(String[] args) {


try
{
int data=50/0; //may throw exception
// if exception occurs, the remaining statement will not exceute
System.out.println("exception will not be printed");
}
// handling the exception
catch(ArithmeticException e)
{
System.out.println(e);
}
System.out.println("rest of the code");
}

Output:

java.lang.ArithmeticException: / by zero
rest of the code
Java Programs on multiple try and catch

public class MultipleCatchBlock {

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");
}
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");
}
}

Output:Arithmetic Exception occurs

rest of the code


Java Programs on nested try catch

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

public class TestFinallyBlock{


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 is always executed");}
System.out.println("rest of the code...");
}
}

Output:Exception in thread main java.lang.ArithmeticException:/ by zero


finally block is always executed
rest of the code...
Java Program on throw keyword

public class TestThrow{

static void validate(int age){

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:

Exception in thread main java.lang.ArithmeticException:not valid


Java Program on throws keyword

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

class MyException extends Exception {


public MyException(String message) {
super(message);
}
}
public class ThrowDemo {
public static void main(String args[]) {
try
{
int a = 10, b = 0, c;

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());
} }}

Output: Caught: Cannot divide by zero


Multithreading in Java


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

✓ It doesn't block the user because threads are independent


and you can perform multiple operations at same time.
✓ You can perform many operations together so it saves
time.
✓ Threads are independent so it doesn't affect other threads
if exception occur in a single thread.
Multitasking

Multitasking is a process of executing multiple tasks simultaneously. We use multitasking to utilize the
CPU. Multitasking can be achieved by two ways:

Process-based Multitasking(Multiprocessing)

Thread-based Multitasking(Multithreading)

1) Process-based Multitasking (Multiprocessing)



Each process has its own address in memory i.e. each process allocates separate memory area.

Process is heavyweight.

Cost of communication between the process is high.

Switching from one process to another require some time for saving and loading registers, memory
maps, updating lists etc.

2) Thread-based Multitasking (Multithreading)



Threads share the same address space.

Thread is lightweight.

Cost of communication between the thread is low.
At least one process is required for each thread.
What is Thread in java

● A thread is a lightweight sub process, a smallest unit of


processing.
● It is a separate path of execution.
● Threads are independent, if there occurs exception in one
thread, it doesn't affect other threads.
● It shares a common memory area.
● At a time one thread is executed only.
Life cycle of a Thread (Thread States)

● A thread can be in one of the five states.


● The life cycle of the thread in java is controlled by JVM.
● The java thread states are as follows:
– New
– Runnable
– Running
– Non-Runnable (Blocked)
– Terminated
Life cycle of a Thread (Thread States)
Life cycle of a Thread (Thread States)
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.
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

class EvenRunnable implements Runnable {


public void run() {
for (int i = 2; i <= 200; i += 2) {
System.out.println("Even Thread: " + i);
}}}
class OddRunnable implements Runnable {
public void run() {
for (int i = 1; i <= 199; i += 2) {
System.out.println("Odd Thread: " + i);
}}}
public class ThreadDemo {
public static void main(String[] args) {
EvenRunnable e = new EvenRunnable();
OddRunnable o = new OddRunnable();
Thread t1 = new Thread(e);
Thread t2 = new Thread(o);
t1.start(); // Start executing the even thread
t2.start(); // Start executing the odd thread
}}
Program of Multithreading using Thread Class

class T1 extends Thread


{
public void run() {
for(int i=1;i<=5;i++) {
System.out.println("Thread1");
try {
Thread.sleep(1000); // Pause execution for 1000 milliseconds (1 second)
} catch (InterruptedException e) {
System.out.println(e);
}}}}

class T2 extends Thread {


public void run() {
for(int i=1;i<=5;i++) {
System.out.println("Thread2");
try {
Thread.sleep(2000); // Pause execution for 2000 milliseconds (2 seconds)
} catch (InterruptedException e) {
System.out.println(e);
}}}}
Program Conti…

public class ThreadDemo {


public static void main(String[] args) {
T1 thread1 = new T1();
T2 thread2 = new T2();
thread1.start(); // Start executing Thread1
thread2.start(); // Start executing Thread2
}
}
Synchronization in Java
Synchronization in java is the capability to control the access of multiple threads to any shared resource.

Java Synchronization is better option where we want to allow only one thread to access the shared resource.

Why use Synchronization

The synchronization is mainly used to

1. To prevent thread interference.


2. To prevent consistency problem.

Program without use of synchronization

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 MyThread1 extends Thread {


Table t;
MyThread1(Table t) {
this.t=t;
}
public void run () {
t.printTable(5);
}
}
class MyThread2 extends Thread {
Table t;
MyThread2(Table t) {
this.t=t;
}
public void run () {
t.printTable(100);
}
}

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

• If you declare any method as synchronized, it is known as synchronized method.


• Synchronized method is used to lock an object for any shared resource.
• When a thread invokes a synchronized method, it automatically acquires the lock for that object and releases it when the
thread completes its task.

//example of java synchronized method


class Table {
synchronized void printTable(int n){//synchronized method
for (int i=1;i<=5;i++){
System.out.println(n*i);
try {
Thread.sleep(400);
} catch (Exception e) {System.out.println(e);}
} } }

class MyThread1 extends Thread {


Table t;
MyThread1(Table t) {
this.t=t;
}
public void run () {
t.printTable(5);
}

}
Program cont..

class MyThread2 extends Thread{


Table t;
MyThread2(Table t){
this.t=t;
}
public void run(){
t.printTable(100);
}
}

public class TestSynchronization2{


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();
}
}

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.

Syntax to use synchronized block


synchronized (object reference expression) {
//code block
}

Example of synchronized block


class Table{

void printTable(int n){


synchronized(this){//synchronized block
for(int i=1;i<=5;i++){
System.out.println(n*i);
try{
Thread.sleep(400);
}catch(Exception e){System.out.println(e);}
}
}
}//end of the method
}
Program cont..

class MyThread1 extends Thread{


Table t;
MyThread1(Table t){
this.t=t;
}
public void run(){
t.printTable(5);
}

}
class MyThread2 extends Thread{
Table t;
MyThread2(Table t){
this.t=t;
}
public void run(){
t.printTable(100);
}
}

public class TestSynchronizedBlock1{


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
10
15
20
25
100
200
300
400
500
Exception Handling in Thread

class MyThread extends Thread{


public void run(){
System.out.println("Throwing in " +"MyThread");
throw new RuntimeException();
}
}
public class Main {
public static void main(String[] args) {
MyThread t = new MyThread();
t.start();
try {
Thread.sleep(1000);
} catch (Exception x) {
System.out.println("Caught it" + x);
}
System.out.println("Exiting main");
}
}
Output:
Throwing in MyThread
Caught exception in MyThread: java.lang.RuntimeException
Exiting main

You might also like