Chapter - 3 Exception Handling - Multithreaded Programming
Chapter - 3 Exception Handling - Multithreaded Programming
Shital Pathar
An exception (or exceptional event) is a problem that arises during the execution of a program.
When an Exception occurs the normal flow of the program is disrupted and the program/Application
terminates abnormally, which is not recommended, therefore these exceptions are to be handled.
An exception is an abnormal condition that arises in a program at run time. In other words, an exception is a
run-time error
When an exception is occurred , creates an exception object and then the normal flow of the program halts and
JRE tries to find someone that can handle the raised exception.
The exception object contains a lot of debugging information such as method hierarchy, line number where the
exception occurred, type of exception etc. When the exception occurs in a method, the process of creating the
exception object and handing it over to runtime environment is called “throwing the exception”.
All exception types are subclasses of a class Throwable. Thus, Throwable is at the top of the exception class
hierarchy.
Throwable
Exception Error
RuntimeException
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 predicated 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
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)
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.
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.
Example:
class Exc2
{
public static void main(String args[])
{
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”);
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 executed 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
}
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”);
}
}
}
Output: e:>java Exc2
a=0
user message : divided by zero
e:>java Exc2 hello
a=1
array index out of bound
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 a=args.length;
System.out.println("a=”+a);
int b=6/a;
int arr[]={1,2,3};
arr[5]=8;
}
catch (Exception e)
{
System.out.println("user message : divided by zero”);
}
catch (ArrayIndexOutOfBoundsException e1)
{
System.out.println("array index out of bound”);
}
}
}
Output: compilation error : exception java.lang. ArrayIndexOutOfBoundsException has already been caught
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[])
{
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.
Example1:
class Exc2
{
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);
}
8. Explain throws() .
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);
}
}
}
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
{
System.out.println("finally block is always executed");
}
System.out.println("rest of the code...");
}
}
Output: finally block is always executed
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.
Thread1
Process2
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.
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 less overhead.
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.
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.
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.It
means thread was created but has not started.
Runnable
When we call start() function on Thread object, it’s state is changed to Runnable. In this state The Thread
scheduler decides which thread runs and how long. but the scheduler has not selected it to be the running
thread.
Running
If a Thread is executing that means Thread is in Running stage.
Blocked
This is the state when the thread is still alive, but is currently not run.
Terminated
Once the thread finished executing, it’s state is changed to terminate and it’s considered to be not alive. when
its run() method exits , Thread reached in terminated state,means it can not run again.
Java’s multithreading system is built upon a Thread class, its methods. and its interface Runnable.
Some methods of Thread class are as below.
extends implements
Thread
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.
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.
Methods:
setPriority : It is used to set the priority of thread.
getPriority : It is used to get the priority of thread.
}
public static void main(String args[])
{
Test m1=new Test();
16. Write a program that executes two threads. One thread will print the even numbers and another thread
will print odd numbers from 1 to 10.
first method:
output:
thread1 1
thread1 3
Synchronized methods:
class display
{
synchronized void show()
{
int i=0;
while(i<4)
System.out.println( i++ );
}
}
class mythread extends Thread
{
display d;
mythread(display d1)
{
d=d1;
}
public void run()
{
d.show();
}
public static void main(String args[]) throws InterruptedException
0 0
1 0
2 1
3 1
0 2
1 2
2 3
3 3
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.
class display
{
void show()
{
int i=0,i1=0;
while(i<4)
System.out.println( "thread name" + i++ );
synchronized(this)
{
while(i1<2)
{
System.out.println( i1 );
i1++;
}
}
}
}
class mythread extends Thread
thread name0
thread name0
thread name1
thread name1
thread name2
thread name2
thread name3
thread name3
0
1
0
1
All uncaught exception are handled by code outside of the run() method before the thread terminates.
But when an unchecked exception is thrown inside the run() method of a Thread object, the default behavior
is to write the stack trace in the console (or log it inside error log file) and exit the program.
It is possible for a program to write a new default exception handler.
Java provides us with a mechanism to catch and treat the unchecked exceptions thrown in a Thread object to
avoid the program ending. This can be done using UncaughtExceptionHandler.
The default exception handler is the uncaught Exception() method of the Thread class. it is called when
exception is thrown from the run() method.
import java.lang.*;
class thread2 extends Thread
{
public void run()
{
System.out.println(10/0);
throw new RuntimeException();
}
public static void main(String[] args)
{
thread2 t=new thread2();
t.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler()
{
public void uncaughtException(Thread t, Throwable e)
{
System.out.println("error in " + t.getName() +e);
}
});
t.start();
}
}
}
output: error in Thread-0 java.lang.ArithmeticException: / by zero
File is a collection of bytes stored in secondary storage device i.e. disk. Thus, File handling is used to read,
write, append or update a file without directly opening it.
Types of File:
Text File
Binary File
Text File contains only textual data. Text files may be saved in either a plain text (.TXT) format and rich text
(.RTF) format like files in our Notepad while Binary Files contains both textual data and custom binary data
like font size, text color and text style etc.
File Handling
The input and output operation that we have performed so far were done through screen and keyboard only.
After the termination of program all the entered data is lost because primary memory is volatile.
A stream is sequence of data.In java a stream is made of bytes.streams are pipelines for sending and receiving
information in java programs.
When a stream of data is sent or received ,it is referred as writing and reading a streamClass.It is called a
stream because it’s like stream of water that continues to flow.
In java, 3 streams are created for us automatically.
1) System.out: standard output stream
2) System.in: standard input stream
3) System.err: standard error stream
java uses streams to handle I/O operations through which the data is flowed from one location to another.
The java Input/Output is a part of java.io package.
InputStream : Java application uses an input stream to read data from a source, it may be a file,an
array,peripheral device or socket.Input stream is automatically opened when you create it.
OutputStream : Java application uses an output stream to write data to a destination, it may be a file,an
array,peripheral device or socket.Output stream is automatically opened when you create it.
InputStream Methods:
read(): it reads bytes of data from a stream
available(): this method returns the number of available bytes that can be read.
close(): it closes the input stream.
skip():it skips n bytes of input.
OutputStreamMethods:
write(): it writes a byte.
available(): this method returns the number of available bytes that can be write.
close(): it closes the output stream.
flush():it flushes the stream. The buffered data is written to the Output stream.
InputStream class
InputStream class is an abstract class.It is the superclass of all classes representing an input stream of bytes.
OutputStream class
OutputStream class is an abstract class.It is the superclass of all classes representing an output stream of bytes.
Java File class represents the files and directory. This class is used for creation of files and directories, file
searching, file deletion, etc.
createNewFile()The java.io.File.createNewFile() method atomically creates a new file named by this abstract
path name and return a boolean value :true or false.
true if the file is created successful; false if the file is already exists or the operation failed.
import java.io.File;
class FileDemo
{
public static void main(String[] args)
{
boolean bool = false;
try
{
File f = new File("test.txt");
bool = f.createNewFile();
System.out.println("File created: "+bool);
}
catch(Exception e)
{
System.out.println("error”);
}
}
}
output: file created true
FileOutputStream class is output stream for writing data to a file.It write data as a form of bytes.For writing
characters use FileWriter.
import java.io.*;
class Test
{
public static void main(String args[])
{
try
{
FileOutputStream fout = new FileOutputStream("abc.txt");
String s="Hello";
byte b[]=s.getBytes(); //converting string into byte array
fout.write(b);
fout.close();
System.out.println("success...");
}
catch(Exception e)
{
system.out.println(e);
}
}
}
23. Write a program to perform read operation from the text file.
FileInputStream class is input stream for reading data from a file.It read data as a form of bytes. For reading
characters use FileReader.
import java.io.*;
class Test
{
import java.io.*;
class Test
{
public static void main(String args[])
{
try
{
FileOutputstream fout=new FileOutputStream("abc1.txt");
FileInputstream fin=new FileInputStream("abc.txt");
int i=0;
while(i=fin.read())!=-1)
fout.write(i);
Generally string is a sequence of characters enclosed within double quotes ex. “java” ,”123”
But in java string is an object. String class is used to create String object.
String objects are stored in a special memory area known as string constant pool inside the Heap memory.
In java strings are immutable it means unmodifiable or unchangeable.
Once string object is created its data or state can not be changed but a new string object is created.
o Creation:
1.Using string literal
2.Using new keyword
String method
1. String length (length)
2. String concate (concat)
3. Changing case (toUpperCase ,toLowerCase)
4. Character extraction (substring , charAt , getChars ,startsWith , endsWith)
5. String comparision (= = , equals, equalsIgnoreCase ,compareTo)
Syntax: stringname.length()
Ex:
class c1
{
public static void main(String args[])
{
String s1=” hello”;
Systemout.println(“length of s1=”+ s1.length());
}
}
Output: length of s1= 5
Syntax: stringname.toUpperCase()
stringname.toLowerCase()
Ex:
class c1
{
public static void main(String args[])
{
String s1=” Hello”;
o substring
A part of string is called substring. it means substring is a subset of another String.
Ex:
class c1
{
public static void main(String args[])
{
String s1=” Hello hi how r u”;
Systemout.println(“substring is =”+s1.substring(6));
Systemout.println(“substring is =”+s1.substring(0,7));
}
}
Output: substring is = hi how r u
substring is = Hello h
o charAt()
Syntax: stringname.charAt(index)
index:it is index of character that you want to display. index value must be integer.
Ex:
class c1
{
public static void main(String args[])
{
String s1=” Hello hi how r u”;
Systemout.println(“single character is =”+s1.charAt(1));
Systemout.println(“single character is =”+s1.charAt(11));
o getChars()
startsWith(string) : this method determines whether a given string begins with a specified string.If string
begin with specified string then true is returned otherwise false is returned.
endsWith(string) : this method determines whether a given string end with a specified string. If string
end with specified string then true is returned otherwise false is returned.
Syntax: stringname.startsWith(string)
stringname.endsWith(string)
Ex:
class c1
{
public static void main(String args[])
{
String s1=” Hello hi how r u”;
Systemout.println(“s1.startsWith(“He”) );
Systemout.println(“s1.startsWith(“ab”) );
Systemout.println(“s1.endsWith(“u”) );
Systemout.println(“s1.startsWith(“r”) );
o equals
This method compare content of string .if content are same then it returns true otherwise it returns false.
Syntax: stringname1.equals(stringname2)
Ex:
class c1
{
public static void main(String args[])
{
String s1=” Hello “;
String s2=”Hello”;
String s3= new String(“Hello”);
String s4=” hi”;
Systemout.println(“s1.equals(s2) );
Systemout.println(“s1.equals(s3) );
Systemout.println(“s1.equals(s4) );
}
}
Output: true
true
false
o equalsIgnorCase
This method compare content of string but it will ignore case . so HELLO and hello is same.
Syntax: stringname1.equalsIgnorCase(stringname2)
Ex:
class c1
{
public static void main(String args[])
{
String s1=” HELLO “;
String s2=”hello”;
o ==
The = = operator compares two object references to see whether they refer to the same instance.If two object
refer same instance the it will return true otherwise it returns false.
Ex:
class c1
{
public static void main(String args[])
{
String s1=” Hello “;
String s2=”Hello”;
String s3= new String(“Hello”);
String s4=” hi”;
Systemout.println(“s1 = = s2 ); // both s1 and s2 refer same instance.
Systemout.println(“s1 = = s3) ); //both s1 and s3 refer different instance.
}
}
Output: true
false
o compareTo
ThecompareTo methos compare values of two string and it returns integer value .
If two strings are same it will return zero
If string1 is greater than string2 then it will return greater than zero.
If string1 is less than string2 then it will return less than zero.
Syntax: stringname1.compareTo(stringname2)
Ex:
class c1
{
public static void main(String args[])
{
String s1=” Hello “;
String s2=”Hello”;
String s3=”hi”;
Systemout.println(s1.compareTo(s2);
Systemout.println (s1.compareTo(s3);
o EX:
StringBuffer s1=new StringBuffer();
StringBuffer s2= new StringBuffer(“hello”);
StringBuffer s3=new StringBuffer(20);
1. length()
2. capacity()
3. append()
4. insert()
5. delete() & deleteCharAt()
6. reverse()
7. replace()
8. charAt()
9. substring()
10. equals()
11. indexof()
1. length()
Syntax: stringname.length()
Ex: class c1
{
2. capacity()
It return allocated capacity of String object. It means how many character can be stored by string.
Syntax: stringname.capacity()
Ex:
class c1
{
public static void main(String args[ ])
{
StringBuffer s1=new StringBuffer();
StringBuffer s2=new StringBuffer("hello");
StringBuffer s3=new StringBuffer(20);
System.out.println(“capacity of s1=”+s1.capacity());
System.out.println((“capacity of s2=”+s2.capacity());
System.out.println((“capacity of s3=”+s3.capacity());
}
}
3. append()
The append() method concat string that is define in(“”) to end of string.
Syntax: stringname.append(string)
Ex:
class c1
{
public static void main(String args[ ])
{
StringBuffer s1=new StringBuffer();
4. insert()
Syntax: stringname.insert(index,string)
Ex: s1.insert(2,”ab”) : insert “ab” into string s1 at 2nd index.
class c1
{
public static void main(String args[ ])
{
StringBuffer s1=new StringBuffer("I java");
System.out.println(s1.insert(2,"like"));
System.out.println(“s1 string=”+s1);
}
}
Output: s1 string= I like java
The deleteCharAt () method delete the character that is specified in the index.
The delete() method deletes sequence of characters from specified start index to end index
Syntax: stringname.deleteChatAt(index)
stringname.delete(startindex,endindex)
class c1
{
public static void main(String args[ ])
{
StringBuffer s1=new StringBuffer("I like java");
6. reverse()
The reverse () method reverse the character that is specified in the string.
Syntax: stringname.reverse()
Ex: class c1
{
public static void main(String args[ ])
{
StringBuffer s1=new StringBuffer("I like java");
s1.reverse();
System.out.println(“string s1=”+s1);
}
}
Output: s1 string= avaj ekil I
7. replace()
The replace () method replace(change) the one set of characters with another set of characters.
Syntax: stringname.replace(startindex,endindex,string)
Ex: s1.replace(2,6,”is”) :change charactes from 2nd index to 5th index by “is” . character which has 6th
index is not changed
class c1
{
public static void main(String args[ ])
{
StringBuffer s1=new StringBuffer("I like java");
s1.replace(2,6,”is”);
System.out.println(“string s1=”+s1);
}
}
Output: s1 string= I is java
LIST OF QUESTIONS: