Chapter - 5 Exception Handling Multithreaded Programming

Download as pdf or txt
Download as pdf or txt
You are on page 1of 24

JAVA PROGRAMMING

Chapter – 5 Exception Handling & Multithreaded programming

1. What is Exception.Explain types of exceptios.


2. Explain what happens when we don’t handle the exceptions? OR Explain uncaught exceptions.
3. Explain Exception handling mechanism with try and catch.
4. Explain multiple catch block with example.
5. Explain unreachable catch block.
6. Explain nested try statement.
7. Explain throw with example.
8. Explain throws with example.
9. Explain finally with example.
10. Explain thread.
11. Explain multithreading and life cycle of thread.
12. List thread class and its methods.
13. How to create thread?
14. Define sleep() method and write program for multithreading .
15. Explain thread priorities with ex.
16. What is synchronization?Explain synchronized block and method.
17. Exception handling in Thread.

1. What is Exception? Explain types of exceptios.

 An exception is an abnormal condition that arises in a program at run time. In other words, an exception is a
run-time error
 An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the
program's instructions.
 When an exception is occurred , an object which represents that exception is created and passed to the method
where the exception has occurred.this object contains detail information about the exception ,which can be
retrived and processed.
 All exception types are subclasses of a class Throwable.Thus, Throwable is at the top of the exception class
hierarchy.

Throwable

Exception Error

RuntimeException

1
JAVA PROGRAMMING

 There are two subclasses of Throwable : Exception and Error.


 Exception class is used for exceptional conditions that user programs should catch. This is also the class that
you will subclass to create your own custom exception types. There is an important subclass of Exception,
called RuntimeException. Exceptions of this type are automatically defined for the programs that you write
and include things such as division by zero and invalid array indexing.
 Error class defines exceptions that are not expected to be caught under normal circumstances by your
program. Exceptions of type Error are used by the Java run-time system. Stack overflow is an example of
such an error.

 Types of Exception:
 There are mainly three types of exceptions

1.Checked Exception.
2.Unchecked Exception.
3.Error.

1.Checked Exception.
 A checked exception is an exception that occurs at the compile time, these are also called as compile time
exceptions. .The exception that can be preditated by the programmer falls under this category.
 For example, File that needs to be opened is not found.

Exception(class) Meaning
ClassNotFoundException A class can not found.
IllegalAccessException An illegal access to a class was attempted
InterruptedException A thread has been interrupted.
NoSuchFieldException A requested field does not exist
NoSuchMethodException A requested method does not exist

2.Unchecked Exception.
 An Unchecked exception is an exception that occurs at the time of execution, these are also called as Runtime
Exceptions, these include programming bugs, such as logic errors or improper use of an API. runtime
exceptions are ignored at the time of compilation.
 For example, if you have declared an array of size 5 in your program, and trying to call the 6th element of the
array .
Exception(class) Meaning
ArithmeticException Such as divide-by-zero
ArrayIndexOutOfBoundsException Array index is out-of-bounds
ArrayStoreException Assignment to an array element of an incompatible type.
ClassCastException Invalid cast

2
JAVA PROGRAMMING

IllegalArgumentException Illegal argument used to invoke a method.


IllegalMonitorStateException Illegal monitor operation, such as waiting on an unlocked thread.
IllegalStateException Environment or application is in incorrect state.
IllegalThreadStateException Requested operation not compatible with current thread state.
IndexOutOfBoundsException Some type of index is out-of-bounds.
NegativeArraySizeException Array created with a negative size.
NullPointerException Invalid use of a null reference
NumberFormatException Invalid conversion of a string to a numeric format.
SecurityException Attempt to violate security
StringIndexOutOfBounds Attempt to index outside the bounds of a string.
UnsupportedOperationException An unsupported operation was encountered.

3.Unrecoverable error.
 These are not exceptions at all, but problems that arise beyond the control of the user or the programmer.
 Errors are typically ignored in your code because you can rarely do anything about an error. For example, if a
stack overflow occurs, an error will arise. This type of error is not possible to handle in code.

2.Explain what happens when we don’t handle the exceptions? OR Explain uncaught exceptions.

 When the Java run-time system detects the exception like divide by zero, it constructs a new exception object
and then throws this exception.
 This exception must be caught by an exception handler. If we don‟t define handler in our program then the
exception is caught by the default handler provided by the Java run-time system.
 The default handler displays a string describing the exception, prints a stack trace from the point at which the
exception occurred, and terminates the program.
 If we define exception handler in our program then exception is handle by our program and appropriate
message is displayed on the screen.
 Ex:
class uncaught
{
public static void main(String args[])
{
int a=0;
int b=7/a;
}
}
 Output:Exception in thread "main" java.lang.ArithmeticException: / by zero at uncaught.main(a.java:6)

3
JAVA PROGRAMMING

 As we don‟t any mechanism for handling exception in the above program,so this will lead to an exception at
runtime and the java run-time system will construct an exception and then throw it.
 Then the default handler will handle the exception and will print the details of the exception.

3. Explain Exception handling mechanism with try and catch.

 Exception handling is the mechanism to handle runtime problems. We need to handle such problems to prevent
abnormal termination of program. So Exception handling mechanism minimizes the chances of a system crash
 Exception handling mechanism provides more specific information about program errors to user.
 Exception Handling is done by transferring the execution of a program to an appropriate exception handler
when exception occurs.
 Exception handler is a block of code to handle thrown exception. If program recover exception then program
can resume executing after the exception handler has executed.
 Exception handlingis done using five keywords, try ,catch, throw, throws, finally.

 try block contains program statements those may generate errors. It means write the code that you want to
monitor inside a try block.
 After try block,include a catch block that specify exception type that you wish to catch.It means catch block
defines a block of statements to handle the generated exception inside the try block.
 If an exception occurs in try block ,the catch block that follows the try is checked,if the type of exception that
occurred match with the catch block then the exception is handed over to the catch block which then handles
it.

 structure of an exception-handling block


try
{
// block of code to monitor for errors
}
catch (ExceptionType1 exOb)
{
// exception handler for ExceptionType1
}
 Here, ExceptionType is the type of exception that has occurred.
 exOb is object.

 Example:
class Exc2
{
public static void main(String args[])

4
JAVA PROGRAMMING

{
int b=0, a=5;
try
{
System.out.println("sum=”+(a+b));
System.out.println("sub=”+(a-b));
System.out.println("div=”+(a/b));
}
catch (ArithmeticException e)
{
System.out.println("system message"+e.getMessage());
System.out.println("user message : divided by zero”);

}
}
}
 Output:
system message/ by zero
user message : divided by zero

4. Explain multiple catch block with example.

 In some cases ,more than one Exception may be generated in try{} block .To handle this type of situation ,you
can specify two or more catch{} block.
 Each catch{} block contain different type of exception.If an exception occurs in the try{} block,the exception
is passed to the first catch{} block in the list.
 If the exception type matches with the first catch{ }block it excuted otherwise it is passed down to the next
catch{} block.
 After one catch{} stat. executes ,the others are bypassed.
 structure
try
{
// block of code to monitor for errors.
}
catch (ExceptionType1 exOb)
{
// exception handler for ExceptionType1

5
JAVA PROGRAMMING

}
catch (ExceptionType2 exOb1)
{
// exception handler for ExceptionType2
}

 Example:
class Exc2
{
public static void main(String args[])
{
try
{
int a=args.length;
System.out.println("a=”+a);
int b=6/a;
int arr[]={1,2,3};
arr[5]=8;
}
catch (ArithmeticException e)
{
System.out.println("user message : divided by zero”);
}
catch (ArrayIndexOutOfBoundsException e1)
{
System.out.println("array index out of bound”);
}

}
}
 Output: e:>java Exc2
a=0
user message : divided by zero
e:>java Exc2 hello
a=1
array index out of bound

5. What is unreachable catch block.

6
JAVA PROGRAMMING

 When you use multiple catch{} statements,it is important that exception subclasses must come before any of
their superclasses.
 This is because a catch{} statement that uses a superclass will catch exceptions of that type plus any of its
subclasses.
 Thus a subclass would never be reached if it came after its superclass.
 Example:
class Exc2
{
public static void main(String args[])
{
try
{
int arr[]={1,2,3};
arr[4]=10/0;
}
catch (Exception e) //this block handles all Exception.
{
System.out.println("user message : divided by zero”);
}
catch (ArrayIndexOutOfBoundsException e1) //this block is unreachable.
{
System.out.println("array index out of bound”);
}
}
}
 Output: compilation error

6. Explain nested try{} blocks.

 The try{} block can be nested.That is try{} block can be inside the block of another try{}.
 Nested try{} block is used when a part of a block may cause one error while entire block may cause another
error.
 In case if inner try{} block does not have a catch handler for a particular exception then the outer try{} block
catch handlers are inspected for a match.

 Example:
class Exc2
{
public static void main(String args[])
{

7
JAVA PROGRAMMING

try
{
int arr[]={0,2,3};
try
{
int a= 2/0;
}
catch (ArithmeticException e)
{
System.out.println("user message : divided by zero”);
}
arr[4]=5;
}
catch (ArrayIndexOutOfBoundsException e1)
{
System.out.println("array index out of bound”);
}
}
}
 Output: user message : divided by zero
array index out of bound

7. Explain throw() .

 when an exception condition occurs the system automatically throw an exception to inform user that there is
something wrong. However we can also throw exception explicitly based on our own defined condition.
 In Java throw keyword is used to explicitly throw an exception.The flow of execution stops immediately after
the throw statement.
 syntax throw Throwableinstance;
 Throwableinstance must be an object of type Throwable or a subclass of Throwable.only object of Throwable
class or its subclasses can be thrown.

 creating instance of Throwable class:


 syntax: classname instancename =new classname(“msg”);
 EX: Throwable t1 = new Throwable(“error”);
 syntax: throw new classname(“msg”);
 EX: throw new ArithmeticException(“error”);

 Example1:
class Exc2

8
JAVA PROGRAMMING

{
public static void main(String args[])
{
Throwable t1=new Throwable(“error”);
try
{
System.out.println("exception is thrown”);
throw t1;
}
catch (Throwable e)
{
System.out.println("exception here : “+e);
}
}
}
 Output: exception is thrown
exception here : error

 Example2:

class Exc2
{
void validate(int age)
{
try
{
if(age<18)
throw new ArithmeticException("not valid");
else
System.out.println("welcome to vote");
}
catch (ArithmeticException e)
{
System.out.println(e);
}
}
public static void main(String args[])
{
Exc2 e1=new Exc2();
e1.validate(13);

9
JAVA PROGRAMMING

}
}
 Output: java.lang.ArithmeticException: not valid

8. Explain throws() .

 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.
 Any method capable of causing exceptions must list all the exceptions possible during its execution, so that
anyone calling that method gets a prior knowledge about which exceptions to handle.
 syntax method_type methodname(parameterlist) throws exception1,exception2,….. ,exception n
{
//body;
}

 Example:

class Test
{
static void check() throws ArithmeticException
{
System.out.println("Inside check function");
throw new ArithmeticException("demo");
}
public static void main(String args[])
{
try
{
check();
}
catch(ArithmeticException e)
{
System.out.println("caught" + e);
}
}
}

 Output: java.lang.ArithmeticException: not valid

10
JAVA PROGRAMMING

9. Explain finally() .

 Sometimes we have situations when a certain piece of code must be executed, no matters if try block is
executed successfully or not, this is done by a „finally‟ block .
 It means “finally” is a keyword that executes a block of statements regardless of whether any exception is
generated or not.
 A „finally‟ block is written followed by a try block or a catch block, code written inside a finally block is
always executed.

 Using a finally block you can execute any cleanup type statements ,return resources to the system ,and execute
other statements like closing file,closing the connection established with database etc..

 Example:

class TestFinallyBlock1
{
public static void main(String args[])
{
try
{
int data=25/0;
System.out.println(data);
}
catch(NullPointerException e)
{
System.out.println(e);
}
finally
{

11
JAVA PROGRAMMING

System.out.println("finally block is always executed");


}
System.out.println("rest of the code...");
}
}
 Output: finally block is always executed

10. Explain thread.

 Process:
 Process is part of computer program that is executed sequentially.

 Thread:
 Thread is lightweight subprocess , a smallest unit of processing.It is a seprate path of execution.
 Threads are independent ,if exception occurs in one thread ,it doesn‟t affect other threads.It share common
memory area.
 Threading is a facility to allow multiple activities to coexist within a single process. Every Java program has at
least one thread -- the main thread. When a Java program starts, the JVM creates the main thread and calls the
program's main() method within that thread.
 The JVM also creates other threads that are mostly invisible to you for example, threads associated with
garbage collection, object finalization.

Process2
Thread1

Thread2
Thread3

Process3

OS
 Thread is executed inside the process.There is context switching between the threads.
 There can be multiple processes inside the OS and one process can have multiple threads.

Process Thread
Processes are heavy weight tasks. Threads are light weight tasks.
Processes requires their own separate address space. Threads share same address spaces.

12
JAVA PROGRAMMING

Context switching from one process to other is costly. Context switching from one thread to other is cheap
compared to process.
Interprocess communication is costly and limited Interthread communication is cheap.
Multitasking processes requires more overhead. Multitasking threads requires more overhead.

11. Explain multithreading and life cycle of thread

 Java is a multi threaded programming language which means we can develop multi threaded program using
Java.Multithreading in java is a process of executing multiple threads simultaneously.
 It means Multithreaded program contains two or more parts that can run simultaneously.For ex. One thread is
writing content on a file at the same time another thread is performing spelling check.
 So single program can perform two or more tasks simultaneously.
 Multithreading enables you to write very efficient programs that make maximum use of the CPU.

 Life cycle of thread:

 There are some states while executing a thread . We define main five states in thread life cycle in java .
 new, runnable, running,blocked, terminated.
 The life cycle of the thread in java is controlled by JVM.

new start() runnable


resume()

blocked
yield() dispatch

terminated thread
completed running sleep

 New
 The thread is in new state if you create an instance of Thread class but before the call of start() method.

 Runnable
 The thread is in runnable state after call of start() method, but the thread scheduler has not selected it to be the
running thread.

 Running
 The thread is in running state if the thread scheduler has selected it.

 Blocked

13
JAVA PROGRAMMING

 This is the state when the thread is still alive, but is currently not run.

 Terminated
 A thread is in terminated or dead state when its run() method exits.

12. List thread class and its methods.

 Java‟s multithreading system is built upon a Thread class, its methods.and its interface Runnable.
 Some methods of Thread class are as below.

getName() Give thread‟s name


setName() change a name of the thread
run() Entry point for the thread
sleep() suspend a thread for a period of time
isAlive() determine whether thread is running or not
join() wait for a thread to terminate
getPriority() give thread‟s priority
setPriority() change priority of thread
suspend() suspends all processes of thread
resume() to resume the execution of suspended thread
stop() stops all processes in the thread.

13. How to create thread?

 There are two ways to create a thread:.


1. Extending java.lang.Thread class
2. Implementing java.lang.Runnable Interface.

extends implements
Thread

Thread (class) Runnable(interface)

 To execute a thread, first thread is created, then


 start() method is invoked on the thread. start() method starts the execution of the thread.JVM calls the run()
method on the thread.
 run() method is used to perform action for a thread.
14
JAVA PROGRAMMING

1. Extending java.lang.Thread class

 For creating thread follow this step:

 create class which extends the java.lang.Thread class.


 write run() method in the subclass from the Thread class .In that we define the code executed by the Thread.
 Create object of this subclass.you mat call Thread class constructor by subclass constructor.
 invoke the start() method on the object of the class to run thread .

 WAP to create single thread

class display extends Thread


{
public void run()
{
System.out.println("thread is running...");
}
public static void main(String args[])
{
display t1=newdisplay();
t1.start();
}
}
 output: thread is running

2. implementing java.lang.Runnable Interface.

 For creating thread follow this step:

 create class which implements the java.lang.Runnable interface.


 write run() method in this class and create object of this class .object of this class is Runnable object.
 create object of Thread class by passing Runnable object as argument.
 invoke the start() method on the object of the thread class.

 WAP to create single thread

class display implements Runnable


{
public void run()

15
JAVA PROGRAMMING

{
System.out.println("thread is running...");
}
public static void main(String args[])
{
display t1=new display();
Thread t2=new Thread(t1);
t2.start();
}
}
 output: thread is running

14. Define sleep() method and write program for multithreading.

 The sleep() method of Thread class is used to sleep a thread for specified amount of time.
 Syntax: sleep( milliseconds)
 it throw InterruptedException type exception.

class Test extends Thread


{
public void run()
{
for(int i=1;i<5;i++)
{
try
{
Thread.sleep(500);
}
catch(InterruptedException e)
{
System.out.println(e);
}
System.out.println(i);
}
}
public static void main(String args[])
{
Test m1=new Test();
Test m2=new Test();
m1.start();

16
JAVA PROGRAMMING

m2.start();
}
}
output: 1
1
2
2
3
3
4
4

15. Explain thread priorities with ex.

 Each thread have a priority. Priorities are represented by a number between 1 and 10.
 In most cases, thread schedular schedules the threads according to their priority (known as preemptive
scheduling). But it is not guaranteed because it depends on JVM specification that which scheduling it chooses.

 There are three constants defined in Thread class:


 Thread.MIN_PRIORITY :The minimum priority of any thread.( value =1)
 Thread.MAX_PRIORITY : The maximum priority of any thread.( value =10)
 Thread.NORM_PRIORITY : The normal priority of any thread.( value =5).This is default priority.

 Methods:
setPriority : It is used to set the priority of thread.
getPriority : It is used to get the priority of thread.

 WAP to demonstration of thread priorities.

class Test extends Thread


{
public void run()
{
System.out.println("running thread name is:"+Thread.currentThread().getName());
System.out.println("running thread priority is:"+Thread.currentThread().getPriority());

}
public static void main(String args[])
{
Test m1=new Test();

17
JAVA PROGRAMMING

Test m2=new Test();


m1.setPriority(Thread.MIN_PRIORITY);
m2.setPriority(Thread.MAX_PRIORITY);
m1.start();
m2.start();
}
}
 output: running thread name is:Thread-0
running thread priority is:1
running thread name is:Thread-1
running thread priority is: 10

16. What is synchronization?Explain synchronized block and method.

 In java while working with multiple threads,it may be possible that more than one thread share the same data at
a time.For ex. one thread read data when other thread tries to change it.This might generate error in result.
 In this case ,it is necessary to allow one thread to finish its task completely and then allow next thread to
execute.So thread Synchronization to allows a programmer to control threads that are sharing data.
 When two or more threads need access to share data,thread synchronization ensure that ,the data will be used
by only one thread at a time.To avoid this problem ,java uses monitor also known as “semaphore” to prevent
data from being loss by multiple threads.
 synchronization is mechanism which allows two or more threads to share all the available resources in a
sequential manner.
 java use synchronized keyword to ensure that only one thread is in a critical region.critical region is area
where only one thread is run at a time.once thread is in its critical region ,no other thread can enter to that
critical region.In this case ,another thread will has to wait until the current thread leaves its critical region.

 There are two ways to synchronized the execution of code.:


 Synchronized methods
 Synchronized blocks(statements).

 Synchronized methods:

 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.

 WAP to demonstration of Synchronized methods .

18
JAVA PROGRAMMING

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);
}
}
class MyThread2 extends Thread
{
Table t;
MyThread2(Table t)
{
this.t=t;
}
public void run()
{

19
JAVA PROGRAMMING

t.printTable(100);
}
}
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: with synchronized method without synchronized method

5 5
10 100
15 10
20 200
25 15
100 300
200 400
300 20
400 25
500 500

 Synchronized block:

 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.

 WAP to demonstration of Synchronized block .

class Table
{
void printTable(int n) //synchronized method
{
synchronized(this)

20
JAVA PROGRAMMING

{
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);
}
}
class MyThread2 extends Thread
{
Table t;
MyThread2(Table t)
{
this.t=t;
}
public void run()
{
t.printTable(100);
}
}

21
JAVA PROGRAMMING

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: with synchronized method without synchronized method

5 5
10 100
15 10
20 200
25 15
100 300
200 400
300 20
400 25
500 500

17. Exception handling in Thread.

 All uncaught exception are handled by code outside of the run() method before the thread terminates.
 It is possible for a program to write a new default exception handler.
 The default exception handler is the uncaughtException() method of the Thread class.it is called when
exception is thrown from the run() method.
 Thread class has two methods for uncaught exception.
 1. setDefaultUncaughtExceptionHandler():
 This method of Thread class can be used to provide a common exception handler for all the threads.
 2. setUncaughtExceptionHandler():
 This non static method of thread class which is used to provide handler to a given thread.

 WAP to demonstration of Synchronized block .

22
JAVA PROGRAMMING

import java.lang.*;

class ThreadDemo
{
public static void main(String[] args)
{
Thread t = new Thread(new adminThread());
t.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler()
{
public void uncaughtException(Thread t, Throwable e)
{
System.out.println("error in " + t.getName() +e.getMessage());
}
});
t.start();
}
}
class adminThread implements Runnable
{
public void run()
{
throw new RuntimeException();
}
}
 output: error in thread -0 null

GTU QUESTION:

1. List four different inbuilt exceptions of java.


2. Write a Java Program to develop user defined exception for „Divide by Zero‟
3. Explain ArrayIndexOutOfBound Exception in Java with example
4. Explain Multiple Catch block with program example.
5. Write a program and explain try…catch block.
6. Explain following (i) throw (ii) finally (i) throws (ii) checked exception

23
JAVA PROGRAMMING

7. Define thread. State two ways to create a thread.


8. Explain thread priorities with ex.
9. Explain life cycle of a thread.
10. Write a program that executes two threads. One thread will print the even numbers and another thread will
print odd numbers from 1 to 50.

24

You might also like