Multi Threading and Exception Handling UPLOAD
Multi Threading and Exception Handling UPLOAD
4
4.1.2 Explain the different types of Thread
Definition
Thread can be defined as single, sequential flow of
control within a program.
Two types
• Single thread
• Multiple threads
5
4.1.2 Explain the different types of Thread
6
4.1.2 Explain the different types of Thread
Multi threaded Application
7
4.1.3 Differentiate between multi-tasking and
multi-threading.
8
Difference Between Multitasking and Multithreading
S.No: Multitasking Multithreading
1. More than one program gets More than one part of a program
executed simultaneously. called threads is executed
simultaneously.
9
4.1.4 Create multi-threaded application
Main Thread
Thread 1 Thread 2
12
Declaring a Thread Class - Example
class Thread_2 extends Thread
{
……………..
……………..
……………..
……………..
……………..
}
13
Declaring a Thread class – Syntax
class <new thread> extends Thread
{
……………..
……………..
……………..
……………..
……………..
}
14
Starting a new Thread - Syntax
Threadname objectname = new Threadname;
objectname.start();
Syntax - objectname.stop();
Example - obj.stop();
18
Methods in Thread Class
Methods Description
19
sleep(t) Used to specify the time frame
for suspension.
20
Life Cycle of a Thread
21
States of Threads
1. Newborn state
2. Runnable state
3. Running state
4. Blocked state
5. Dead state.
22
States Description
23
4.0 MULTI THREADING AND EXCEPTION HANDLING
26
When an error occurs within a method, the method creates an
object and hands it off to the runtime system.
The object, called an exception object, contains information
about the error, including its type and the state of the program
when the error occurred.
Creating an exception object and handing it to the runtime
system is called throwing an exception.
After a method throws an exception, the runtime system
attempts to find something to handle it.
The set of possible "somethings" to handle the exception is the
ordered list of methods that had been called to get to the method
where the error occurred.
The list of methods is known as the call stack 27
The call stack.
28
The runtime system searches the call stack for a method
that contains a block of code that can handle the exception.
This block of code is called an exception handler.
The search begins with the method in which the error
occurred and proceeds through the call stack in the reverse
order in which the methods were called.
When an appropriate handler is found, the runtime system
passes the exception to the handler.
An exception handler is considered appropriate if the type
of the exception object thrown matches the type that can
be handled by the handler.
29
The exception handler chosen is said to catch the exception.
If the runtime system exhaustively searches all the methods on the
call stack without finding an appropriate exception handler, as shown
in the next figure, the runtime system (and, consequently, the
program) terminates.
30
An exception is a problem that arises during the execution of a program.
An exception can occur for many different reasons, including the
following:
• A user has entered invalid data.
• A file that needs to be opened cannot be found.
• A network connection has been lost in the middle of
communications, or the JVM has run out of memory.
31
Three categories of exceptions:
1. Checked exceptions:
A checked exception is an exception that is typically a user
error or a problem that cannot be foreseen by the
programmer.
For example, if a file is to be opened, but the file cannot
be found, an exception occurs.
These exceptions cannot simply be ignored at the time of
compilation.
32
2. Runtime exceptions:
A runtime exception is an exception that occurs that
probably could have been avoided by the programmer.
As opposed to checked exceptions, runtime exceptions
are ignored at the time of compilation.
33
3. Errors:
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.
They are also ignored at the time of compilation.
34
All exception classes are subtypes of the java.lang.Exception class.
The exception class is a subclass of the Throwable class. Other than
the exception class there is another subclass called Error which is
derived from the Throwable class.
35
4.2.2 Explain the use of exception handling
37
Example:
class Excep1{
public static void main(String args[]){
int A,B,C=0;
A=Integer.parseInt(args[0]);
B=Integer.parseInt(args[1]);
try {
C= A/B; // B have value of 0,exception will occur
}
catch(ArithmeticException ae){
System.out.println("Caught Exception :- " + ae.getMessage());
}
System.out.println("The Value of C:- " + C);
} ictl}
38
Output:
C:\Program Files\Java\jdk1.6.0_27\bin>java Excep1 0 2
The Value of C:- 0
39
• The above example, declares 3 variables A, B and C in line 6.
• If the user enters the value 0 for B, the statement C = A/B in line 11
generates an Arithmetic Exception.
• So this statement is put inside the try block. If you have a try block
then you should have catch block to handle the Exception.
• In the catch block, an object ae is created for the ArithmeticException
type in line 13.
• The catch block catches the Arithmetic Exception. The object ae holds
the reference of the exception.
• Using the getMessage() method the content of the exception is
displayed in line 15. if try and catch blocks are not used then the
program terminates abruptly.
40
Multiple catch Blocks:
• A try block can be followed by multiple catch blocks. The syntax for
multiple catch blocks looks like the following:
try {
//Protected code
}catch(ExceptionType1 e1) {
//Catch block }catch(ExceptionType2 e2) {
//Catch block }catch(ExceptionType3 e3) {
//Catch block }
41
42
The above example contains two catch statements. The statement c=a/b
in line 10 will generate Arithmetic Exception and int var = arr[2]-arr[1] in
line 11 will generate ArrayIndexOutOfBound Exception.
The Arithmetic Exception is raised first and hence the control
automatically jumps to corresponding catch statement. The statement
System.out.println("Arithmetic Exception") is executed and the the
ArithmeticException is printed on the monitor.
43
A sample program to illustrate the use of Exception class to catch any
type of exception generated by the program
class ExcepClassDemo{
public static void main(String args[]){
int a=Integer.parseInt(args[0]);
int b=Integer.parseInt(args[1]);
int c;
int arr[]={10,20};
try{
c=b/a;
int arr[2] = arr[1]-arr[0];
}catch (Exception e){
System.out.println("Exception Generated");
}}}
44
Till now you have written programs to catch exceptions thrown by
Java run-time system. The throw statement allows you to throw
exceptions that are not thrown by Java run-time system . When
throw is used inside the program, it implies that the program is going
to throw an exception.
Syntax
throw new exceptiontype ();
45
class ThrowDemo{
public static void main(String args[]) {
int x=Integer.parseInt(args[0]);
int y=Integer.parseInt(args[1]);
try {
float z = (float)x/(float)y;
if(z<0.01)
throw new Exception("Number is too small");
} catch(Exception e) {
System.out.println("Caught the exception:- " +
e.getMessage());
}
System.out.println("The value of z:- Output:
" + z);
}} C:\java>java ThrowDemo 1 100
Caught the exception:- Number is too small
The value of z:- 0.01
The finally block
• If you define a finally block it will surely execute, regardless of whether the
exception is thrown or not.
• The finally block contains statements for doing the final process such as
deallocation of memory etc.
• It may be added immediately after the try block or after the last catch block.
• A try block should have at least one catch block or finally block immediately
following it.
Syntax: finally{
statements ;// code to be executed
}
Example: finally{
System.out.println("These statements will be executed regardless of
whether an exception is thrown or not");
}
Example:
class FinallyDemo{
public static void main(String args[]){
int a=0,b=5,c=0; Output:
C:\java>javac FinallyDemo.java
try{ C:\java>java FinallyDemo
c=b/a; I will execute if the exception is generated
I always execute at last
}catch(ArithmeticException e){
System.out.println("I will execute if the exception is
generated");
}finally {
System.out.println("I always execute at last");
} } }
Creating User-Defined Exceptions
• The built-in exceptions in Java handle most of the common errors. In
some situations you need to handle exceptions that are specific to
your applications.
• Consider that you are developing an application in Java for a
company.
• The code may raise an exception in certain situation. The exception,
which is raised, is only specific for that application.
• If this exception generated is not defined in the built-in exceptions of
Java, then you need to create a user-defined exception, which can
handle the situation
• When you want to create user-defined exception, it should be the sub
class of class Throwable.
• The class Exception is the subclass for the class Throwable. Therefore
all the user-defined exceptions are subclasses of the class Throwable
Example: try{
import java.lang.Exception; float c=(float)a/(float)b;
class MyException extends if(c>0.01)
Exception{ {
MyException(String message){ throw new MyException("The
System.out.println(message); Number is greater than 0.01");
} }
} }
class UserExcep{ catch(MyException myexcep)
public static void main(String {
args[]){ System.out.println("Caught
int a=2,b=100; my exception");
Continue }}}
4.2.3 Explain the different types of exceptions in
RuntimeException
a. NumberFormatException
public class NumberFormatException extends
IllegalArgumentException
NumberFormatException()
Constructs a NumberFormatException with no detail message
NumberFormatException(String s)
Constructs a NumberFormatException with the specified detail
message.
4.2.3 Explain the different types of exceptions in
RuntimeException
b. ArrayIndexOutOfBoundsException
public class ArrayIndexOutOfBoundsException extends
IndexOutOfBoundsException
Thrown to indicate that an array has been accessed with an illegal index.
The index is either negative or greater than or equal to the size of the
array
4.2.3 Explain the different types of exceptions in
RuntimeException
c. ArithmeticException
public class ArithmeticException extends RuntimeException
Thrown to indicate that an attempt has been made to store the wrong
type of object into an array of objects. For example, the following code
generates an ArrayStoreException:
Object x[] = new String[3];
x[0] = new Integer(0);
4.2.3 Explain the different types of exceptions in
RuntimeException
blic
e. ClassCastException
Thrown
classtoClassCastException
indicate that the code has attempted
extends to cast an object to a
RuntimeException
subclass of which it is not an instance.