20mca22c U3
20mca22c U3
Unit – III
EXCEPTION HANDLING
FACULTY
Dr. K. ARTHI MCA, M.Phil., Ph.D.,
Assistant Professor,
Postgraduate Department of Computer Applications,
Government Arts College (Autonomous),
Coimbatore – 641 018.
Exception Handling in Java
1. Exception Handling
2. Advantage of Exception Handling
3. Hierarchy of Exception classes
4. Types of Exception
5. Exception Example
6. Scenarios where an exception may occur
The Exception Handling in Java is one of the powerful mechanism to handle the runtime errors so that normal flow of the
application can be maintained.
In this page, we will learn about Java exceptions, its type and the difference between checked and unchecked exceptions.
In Java, an exception is an event that disrupts the normal flow of the program. It is an object which is thrown at runtime.
The core advantage of exception handling is to maintain the normal flow of the application. An exception normally
disrupts the normal flow of the application that is why we use exception handling. Let's take a scenario:
1. statement 1;
2. statement 2;
3. statement 3;
4. statement 4;
5. statement 5;//exception occurs
6. statement 6;
7. statement 7;
8. statement 8;
9. statement 9;
10. statement 10;
Suppose there are 10 statements in your program and there occurs an exception at statement 5, the rest of the code will not
be executed i.e. statement 6 to 10 will not be executed. If we perform exception handling, the rest of the statement will be
executed. That is why we use exception handling in Java.
1. Checked Exception
2. Unchecked Exception
3. Error
Difference between Checked and Unchecked Exceptions
1) Checked Exception
The classes which directly inherit Throwable class except RuntimeException and Error are known as checked exceptions e.g.
IOException, SQLException etc. Checked exceptions are checked at compile-time.
2) Unchecked Exception
The classes which inherit RuntimeException are known as unchecked exceptions e.g. ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException etc. Unchecked exceptions are not checked at compiletime, but they are checked at runtime.
3) Error
next →← prev
The Exception Handling in Java is one of the powerful mechanism to handle the
runtime errors so that normal flow of the application can be maintained.
In this page, we will learn about Java exceptions, its type and the difference between
checked and unchecked exceptions.
. statement 3;
. statement 4;
. statement 6;
. statement 7;
. statement 8;
. statement 9;
0. statement 10;
Do You Know?
o What are the 4 rules for using exception handling with method
overriding?
1. Checked Exception
2. Unchecked Exception
3. Error
2) Unchecked Exception
Test it Now
1. int a=50/0;//ArithmeticException
If we have a null value in any variable, performing any operation on the variable throws a NullPointerException.
1. String s=null;
2. System.out.println(s.length());//NullPointerException
The wrong formatting of any value may occur NumberFormatException. Suppose I have a string variable that has characters,
converting this variable into digit will occur NumberFormatException.
1. String s="abc";
2. int i=Integer.parseInt(s);//NumberFormatException
If you are inserting any value in the wrong index, it would result in ArrayIndexOutOfBoundsException as shown below:
A thread is a lightweight sub-process, the smallest unit of processing. Multiprocessing and multithreading, both are used to
achieve multitasking.
However, we use multithreading than multiprocessing because threads use a shared memory area. They don't allocate separate
memory area so saves memory, and context-switching between the threads takes less time than process.
3) Threads are independent, so it doesn't affect other threads if an exception occurs in a single thread.
Creating a thread
There are two ways to create a thread:
1. By extending Thread class
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.
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().
Starting a thread:
start() method of Thread class is used to start a newly created
thread. It performs following tasks:
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.
Types of Synchronization
There are two types of synchronization
1. Process Synchronization
2. Thread Synchronization
Thread Synchronization
There are two types of thread synchronization mutual exclusive and inter-thread communication.
1. Mutual Exclusive
1. Synchronized method.
2. Synchronized block.
3. static synchronization.
2. Cooperation (Inter-thread communication in java)
Mutual Exclusive
Mutual Exclusive helps keep threads from interfering with one another while sharing data. This can be done by three ways in
java:
1. by synchronized method
2. by synchronized block
3. by static synchronization
1. class Table{
2. void printTable(int n){//method not synchronized
3. for(int i=1;i<=5;i++){
4. System.out.println(n*i);
5. try{
6. Thread.sleep(400);
7. }catch(Exception e){System.out.println(e);}
8. }
9.
10. }
11. }
12.
13. class MyThread1 extends Thread{
14. Table t;
15. MyThread1(Table t){
16. this.t=t;
17. }
18. public void run(){
19. t.printTable(5);
20. }
21.
22. }
23. class MyThread2 extends Thread{
24. Table t;
25. MyThread2(Table t){
26. this.t=t;
27. }
28. public void run(){
29. t.printTable(100);
30. }
31. }
32.
33. class TestSynchronization1{
34. public static void main(String args[]){
35. Table obj = new Table();//only one object
36. MyThread1 t1=new MyThread1(obj);
37. MyThread2 t2=new MyThread2(obj);
38. t1.start();
39. t2.start();
40. }
41. }
Output: 5
100
10
200
15
300
20
400
25
500
When a thread invokes a synchronized method, it automatically acquires the lock for that object and releases it when the
thread completes its task.
4. for(int i=1;i<=5;i++){
5. System.out.println(n*i);
6. try{
7. Thread.sleep(400);
8. }catch(Exception e){System.out.println(e);}
9. }
10.
11. }
12. }
13.
14. class MyThread1 extends Thread{
15. Table t;
16. MyThread1(Table t){
17. this.t=t;
18. }
19. public void run(){
20. t.printTable(5);
21. }
22.
23. }
24. class MyThread2 extends Thread{
25. Table t;
26. MyThread2(Table t){
27. this.t=t;
28. }
29. public void run(){
30. t.printTable(100);
31. }
32. }
33.
34. public class TestSynchronization2{
35. public static void main(String args[]){
36. Table obj = new Table();//only one object
37. MyThread1 t1=new MyThread1(obj);
38. MyThread2 t2=new MyThread2(obj);
39. t1.start();
40. t2.start();
41. }
42. }
Output: 5
10
15
20
25
100
200
300
400
500
Cooperation (Inter-thread communication) is a mechanism in which a thread is paused running in its critical section and
another thread is allowed to enter (or lock) in the same critical section to be executed.It is implemented by following methods
of Object class:
o wait() o notify()
o notifyAll()
1) wait() method
Causes current thread to release the lock and wait until either another thread invokes the notify() method or the notifyAll()
method for this object, or a specified amount of time has elapsed.
The current thread must own this object's monitor, so it must be called from the synchronized method only otherwise it will
throw exception.
Method Description
2) notify() method
Wakes up a single thread that is waiting on this object's monitor. If any threads are waiting on this object, one of them is
chosen to be awakened. The choice is arbitrary and occurs at the discretion of the implementation. Syntax: public final void
notify()
3) notifyAll() method
Wakes up all threads that are waiting on this object's monitor. Syntax: public final void
notifyAll()
Why wait(), notify() and notifyAll() methods are defined in Object class not Thread class?
It is because they are related to lock and object has a lock.
wait() sleep()