unit III
unit III
NOTES
Page 1
Page 2
UNIT III - EXCEPTION HANDLING AND
MULTITHREADING
SL NO TOPIC
UNIT – III : Syllabus with PL
1 EXCEPTION HANDLING BASICS
2 MULTIPLE CATCH CLAUSES
3 NESTED TRY STATEMENTS
4 JAVA’S BUILT-IN EXCEPTIONS
5 USER DEFINED EXCEPTION
6 MULTITHREADED PROGRAMMING: JAVA
THREAD MODEL
7 CREATING A THREAD AND MULTIPLE
THREADS
8 PRIORITIES
9 SYNCHRONIZATION
10 INTER THREAD COMMUNICATION
11 SUSPENDING
12 RESUMING, AND STOPPING THREADS
13 MULTITHREADING
14 WRAPPERS
15 AUTO BOXING
Page 3
1. EXCEPTION HANDLING BASICS
Exception Handler
Procedure and description:
1) When an unexpected error occurs in a method, java creates an object of the
appropriate exception class.
2) After creating the exception object, java passes it to the program, by an action
called throwing an exception.
3) The exception object contains information about the type of error and the state of
the program when the exception occurred.
Page 4
4) You need to handle the exception using exception-handler and process the exception.
You can implement exception handling in your program by using try, catch, throw, throws
and finally keywords
• The try-catch block is used to handle exceptions in Java.
• This code block is called Exception handler.
try {
// code
}
catch(Exception e) {
// code
}
finally {
// finally block always executes
}
Page 5
Example:
{ try {
Output
Page 6
Uncaught Exceptions
This small program includes an expression that intentionally causes a divide-by- zero error:
class Exc0 {
public static void main(String args[])
{
int d = 0; int a =42 / d;
}
}
Here is the exception generated when this example is executed:
java.lang.ArithmeticException: / by zero at Exc0.main(Exc0.java:4)
Page 7
Error in Java
• Errors are problems that mainly occur due to the lack of system resources.
• It cannot be caught or handled. It indicates a serious problem.
• It occurs at run time.
• These are always unchecked. An example of errors is
OutOfMemoryError, LinkageError, AssertionError, etc. are the subclasses of
the Error class.
Exception in java
• Exception is an abnormal condition.
• 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 general meaning of exception is a deliberate act of omission while the meaning
of error is an action that is inaccurate or incorrect.
• In Java, Exception, and Error both are subclasses of the Java Throwable class
that belongs to java.lang package.
Errors Exception
On the other hand, the exceptions occur
The error implies a problem that mostly
during runtime and compile time.
arises due to the shortage of system
resources.
Exception Handling is a mechanism to handle
Errors indicate serious problems and
runtime errors.
abnormal conditions that most applications
should not try to handle.
An exception normally disrupts the normal
Error defines problems that are not
flow of the application; that is why we need
expected to be caught under normal
to handle exceptions.
circumstances by our program.
Example: ClassNotFoundException,
For example memory error, hardware error, IOException, SQLException,
JVM error etc. RemoteException, etc.
Types of Exceptions
• The parent class of all the exception classes is the java.lang.Exception class.
Page 8
Page 9
• The Exception class is a subclass of the built-in Throwable class.
• There are mainly two types of exceptions in Java as follows:
a) Checked exception
b) Unchecked exception
• There is another subclass which is derived from the Throwable class i.e. Error
as illustrated in Figure 1.
• The error can be defined as an abnormal condition that indicates something has gone
wrong with the execution of the program.
• These are not handled by Java programs.
Exceptions
Few examples
• DivideByZero exception
• NullPointerException
• ArithmeticException
• ArrayIndexOutOfBoundsException
o An exception (or exceptional event) is a problem that arises during the execution of a
program.
o 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.
o If an exception is raised, which has not been handled by programmer then
program execution can get terminated and system prints a non user friendly error
message.
Where, ExceptionDemo : The class name main : The method name ExceptionDemo.java
: The filename java:5 : Line number
Page 10
Why Exceptions?
Page 11
An exception can occur for many different reasons.
Following are some scenarios where an exception occurs.
a) A user has entered an invalid data.
b) A file that needs to be opened cannot be found.
c) A network connection has been lost in the middle of communications or the
JVM has run out of memory.
Exception Hierarchy
• All exception classes are subtypes of the java.lang.Exception class.
• The exception class is a subclass of the Throwable class.
2. catch A catch statement involves declaring the type of exception we are trying
to catch.
Page 12
catch(ExceptionType1 e1)
Page 13
try
{
{
System.out.println("Access element three :" +a[3]);
//Catch block
}
} catch(ArrayIndexOutOfBoundsException e)
catch(ExceptionType2 e2) {
System.out.println("Exception thrown :" + e);
{ }
//Catch block
Finally
{
a[0] = 6;
}
catch(ExceptionType3 e3)
{
System.out.println("First element value: " + a[0]);
//Catch block
}
}
}
finally
{
System.out.println("The finally statement is executed");
}
Output
Page 14
Checked exception
• Checked exceptions are also known as compile-time exceptions as these exceptions are
checked by the compiler during the compilation process to confirm whether the exception
is handled by the programmer or not.
• If not, then the system displays a compilation error.
i) IOException,
ii) SQLException
iii) InvocationTargetException
iv) ClassNotFoundException.
i) IOException
To illustrate the concept of checked exception, let us consider the following code snippet:
// IOexpdemo.java
import java.io.*;
class IOexpdemo {
public static void main(String args[])
{ FileInputStream input1 = null;
Page 15
// The close() will close the file input stream, and it will also throw a exception
input1.close();
}
}
Output:
throw keyword
• It is clearly displayed in the output that the program throws exceptions during
the compilation process.
• There are two methods of resolving such issues.
• You can declare the exception with the help of the throw keyword.
• The Java throw keyword is used to explicitly throw a single exception.
• When we throw an exception, the flow of the program moves from the try block to
the catch block.
Example 01:
// throw an exception
throw new ArithmeticException("Trying to divide by 0");
}
Page 16
}
Output
Note:
In the above code, we are explicitly throwing the ArithmeticException using the throw
keyword.
Example 2:
// File Open exception Handler code
import java.io.*;
class demo1 {
public static void main(String args[]) throws IOException
{ FileInputStream input1 = null;
input1 = new FileInputStream("D:/file.txt");
int m;
while ((m = input1.read()) != -1) {
System.out.print((char)m);
}
input1.close();
}
}
Output: The file will be displayed on the screen.
try-catch block
Apart from the above-mentioned method, there is another way to resolve exceptions. You
can manage them with the help of try-catch blocks.
Page 17
import java.io.*;
class demo1 {
public static void main(String args[])
{ FileInputStream input1 = null;
try {
input1 = new FileInputStream("D:/file.txt");
} catch(FileNotFoundException input2) {
System.out.println("The file does not " + "exist at the location");
}
int m;
try {
while((m = input1.read()) != -1) {
System.out.print((char)m);
}
input1.close();
} catch(IOException input3)
{ system.out.println("I/O error occurred: "+
input3);
}
}
}
Output: The code will run smoothly and the file will be displayed.
// expThrowsexample .java code that Java throws for File not found
import java.io.*;
class expThrowsexample {
Page 18
// declareing the type of exception
public static void findFile() throws IOException {
Page 19
// code that may generate IOException
File newFile = new File("test.txt");
FileInputStream stream = new FileInputStream(newFile);
}
Output
i) IOException
• This type of exception occurs while using file I/O stream operations.
import java.io.*;
public class sample_IOException {
private static String filepath = "D:\User\guest\Desktop\File2.txt";
Page 20
public static void main(String[] args)
{ BufferedReader br1 = null;
String curline;
try {
br1 = new BufferedReader(new FileReader(filepath));
ii) SQLException
This type of exception occurs while executing queries on a database related to the SQL
syntax. For example, consider the following code snippet:
Page 21
try {
checkAndFireConnectionError(sqlEx);
} catch (SQLException sqlEx2) {
SQLClientInfoException client_Ex = new SQLClientInfoException();
client_Ex.initCause(sqlEx2);
throw client_Ex;
}
}
}
Output:
This code will generate a SQLException.
iii) ClassNotFoundException
This type of exception is thrown when the JVM is not able to find the required class.
It may be due to a command-line error, a classpath issue, or a missing .class file.
For example, consider the following code snippet:
iv) InvocationTargetException
Page 22
This type of exception wraps an exception thrown by an invoked method or
a constructor.
The thrown exception can be accessed with the help of the
getTargetException method.
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class Example {
private int test_sample(String s1)
{ if (s1.length() == 0)
throw new IllegalArgumentException("The string should have at least one
character!");
System.out.println("Inside test_sample: argument's value equals to: "" + s1 + """);
return 0;
}
try {
method.setAccessible(true);
Object returnValue = method.invoke(t1, "");
System.out.format("%s() returned: %d%n", methodName, returnValue);
} catch (InvocationTargetException ex) {
System.err.println("An InvocationTargetException was caught!");
Page 23
Throwable cause = ex.getCause();
System.out.format("Invocation of %s failed because of: %s%n",
methodName, cause.getMessage());
}
}
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException
ex) {
System.err.println("The following exception was thrown:");
ex.printStackTrace();
}
}
}
Output:
Invoking testMethod()
An InvocationTargetException was caught!
Invocation of testMethod failed because of: The string must contain at least one character!
Output: This code will generate an InstantiationException.
Unchecked exception
• The unchecked exceptions are those exceptions that occur during the execution of
the program. Hence they are also referred to as Runtime exceptions.
• These exceptions are generally ignored during the compilation process.
• They are not checked while compiling the program.
• For example, programming bugs like logical errors, and using incorrect APIs.
i) NullPointerException
ii) ArrayIndexOutofBound
iii) IllegalArgumentException
iv) IllegalStateException
v) NumberFormatException
vi) ArithmeticException
Example
Page 24
To illustrate the concept of an unchecked exception, let us consider the following code
snippet:
import java.util.Scanner;
public class Sample_RunTimeException
{ public static void main(String[] args) {
// Reading user input
Scanner input_dev = new Scanner(System.in);
System.out.print("Enter your age in Numbers: ");
int age1 = input_dev.nextInt();
if (age1>20) {
System.out.println("You can view the page");
} else {
System.out.println("You cannot view the page");
}
}
}
Output 1:
i) NullPointerException
This type of exception occurs when you try to access an object with the help of a reference
variable whose current value is null or empty. For example, consider the following code
snippet:
Page 25
// Program to demonstrate the NullPointerException
class SampleNullPointer {
public static void main(String args[])
{ try {
String a1 = null; // null value
System.out.println(a1.charAt(0));
} catch(NullPointerException e)
{ System.out.println("NullPointerException is found in the
program.");
}
}
}
Output: NullPointerException is found in the program.
ii) ArrayIndexOutofBound
This type of exception occurs when you try to access an array with an invalid index value.
The value you are providing is either negative or beyond the length of the array.
iii) IllegalArgumentException
This type of exception occurs whenever an inappropriate or incorrect argument is passed to
Page 26
a method. For example, if a method is defined with non-empty string as parameters. But
Page 27
you are providing null input strings. Then, the IllegalArgumentException is thrown to
indicate the user that you cannot pass a null input string to the method.
import java.io.File;
public class Sample_IllegalArgumentException {
public static String createRelativePath(String par, String f_name)
{ if (par == null)
throw new IllegalArgumentException("You cannot provide null parent path!");
if (f_name == null)
throw new IllegalArgumentException("Please enter the complete filename!");
iv) IllegalStateException
This type of exception occurs when the state of the environment does not match the
operation being executed.
Page 28
For example, consider the following code snippet, which demonstrates this type of
exception:
/**
* This code will publish the current book.
* If the book is already published, it will throw an IllegalStateException.
**/
public void pub() throws IllegalStateException {
Date pub_at = getPub_at();
if (pub_at == null)
{ setPub_at(new Date());
Logging.log(String.format("Published '%s' by %s.", getTitle(), getAuthor()));
} else {
throw new IllegalStateException(
String.format("Cannot publish '%s' by %s (already published on %s).",
getTitle(), getAuthor(), pub_at));
}
}
Output: This code will generate IllegalStateException.
v) NumberFormatException
This type of exception occurs when you pass a string to a method that cannot be converted
to a number. For example, consider the following code snippet:
Page 29
System.out.println("Number format exception");
}
}
}
Output: This code will generate NumberFormatException.
vi) ArithmeticException
This type of exception occurs when you perform an incorrect arithmetic operation. For
example, if you divide any number by zero, it will display such an exception. Let us
consider the following code snippet:
Stack Trace:
• Stack Trace is a list of method calls from the point when the application was started
to the point where the exception was thrown.
• The most recent method calls are at the top.
• A stacktrace is a very helpful debugging tool. It is a list of the method calls that
the application was in the middle of when an Exception was thrown.
• This is very useful because it doesn't only show you where the error happened, but
also how the program ended up in that place of the code.
Page 30
Using try and Catch
• To guard against and handle a run-time error, simply enclose the code that you want to
monitor inside a try block.
• Immediately following the try block, include a catch clause that specifies the
exception type that you wish to catch.
• A try and its catch statement form a unit.
The the following program includes a try block and a catch clause that processes the
ArithmeticException generated by the division-by-zero error:
class Exc2 {
public static void main(String args[])
{ int d, a;
try {
// monitor a block of code. d = 0;
a = 42 / d;
System.out.println("This will not be printed.");
} catch (ArithmeticException e)
{ // catch divide-by-zero error
System.out.println("Division by zero.");
}
System.out.println("After catch statement.");
}
}
Page 31
2. Multiple catch Clauses
In some cases, more than one exception could be raised by a single piece of code.
To handle this type of situation, you can specify two or more catch clauses,
each catching a different type of exception.
When an exception is thrown, each catch statement is inspected in order, and the
first one whose type matches that of the exception is executed.
After one catch statement executes, the others are bypassed, and execution
continues after the try/catch block.
Page 32
• An inner try statement does not have a catch handler for a particular exception,
the stack is unwound and the next try statement’s catch handlers are inspected for a
match.
• This continues until one of the catch statements succeeds, or until all of the nested
try statements are exhausted.
• If no catch statement matches, then the Java run-time system will handle the exception.
Example
// An example of nested try statements.
class NestTry {
public static void main(String args[]) { try {
int a = args.length;
/* If no command-line args are present, the following statement will generate
a divide-by-zero exception. */ int b = 42 / a; System.out.println("a = " + a); try { // nested
try block
/* If one command-line arg is used, then a divide-by-zero exception
will be generated by the following code. */ if(a==1) a = a/(a-a); // division by zero
/* If two command-line args are used,
then generate an out-of-bounds exception. */
if(a==2) {
int c[] = { 1 };
C:\>java NestTry
Divide by 0: java.lang.ArithmeticException: / by zero C:\>java NestTry One
a=1
Divide by 0: java.lang.ArithmeticException: / by zero C:\>java NestTry One Two
a=2
Array index out-of-bounds: java.lang.ArrayIndexOutOfBoundsException:42
throw
It is possible for your program to throw an exception explicitly, using the throw statement.
The general form of throw is shown here:
throw ThrowableInstance;
Page 35
} catch(NullPointerException e) { System.out.println("Caught inside demoproc."); throw e;
// rethrow the exception
}
}
public static void main(String args[]) { try {
demoproc();
} catch(NullPointerException e) { System.out.println("Recaught: " + e);
}
}
}
Throws
• If a method is capable of causing an exception that it does not handle, it must
specify this behaviour so that callers of the method can guard themselves against that
exception.
• You do this by including a throws clause in the method’s declaration.
• A throws clause lists the types of exceptions that a method might throw. This is
necessary for all exceptions, except those of type Error or RuntimeException, or any
of their subclasses.
• All other exceptions that a method can throw must be declared in the throws clause.
• This is the general form of a method declaration that includes a throws clause:
Here, exception-list is a comma-separated list of the exceptions that a method can throw.
class ThrowsDemo {
Page 36
Page 37
static void throwOne() throws IllegalAccessException { System.out.println("Inside
throwOne.");
throw new IllegalAccessException("demo");
}
public static void main(String args[]) { try {
throwOne();
} catch (IllegalAccessException e)
{ System.out.println("Caught " + e);
}
}
}
Here is the output generated by running this example program: inside throwOne
caught java.lang.IllegalAccessException: demo
finally
• The finally keyword is designed to address this contingency.
• finally creates a block of code that will be executed after a try/catch block
has completed and before the code following the try/catch block.
• The finally block will execute whether or not an exception is thrown.
• If an exception is thrown, the finally block will execute even if no catch
statement matches the exception.
• Any time a method is about to return to the caller from inside a try/catch block, via
an uncaught exception or an explicit return statement, the finally clause is also executed
just before the method returns.
This can be useful for closing file handles and freeing up any other resources that might
have been allocated at the beginning of a method with the intent of disposing of them before
returning.
The finally clause is optional.
Page 38
System.out.println("procA's finally");
}
}
// Return from within a try block. static void procB()
{ try {
System.out.println("inside procB"); return;
} finally { System.out.println("procB's finally");
}
}
// Execute a try block normally. static void procC() {
try {
System.out.println("inside procC");
} finally { System.out.println("procC's finally");
}
}
public static void main(String args[]) { try {
procA();
} catch (Exception e) { System.out.println("Exception caught");
}
procB();
procC();
}
}
Here is the output generated by the preceding program:
inside procA procA’s finally Exception caught inside procB procB’s finally inside procC
procC’s finally
Categories of Exceptions
Page 39
2) Unchecked exceptions − An unchecked exception is an exception that occurs at
thetime 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.
Page 40
User defined exception needs to inherit (extends) Exception class in order to act as an
exception.
throw keyword is used to throw such exceptions.
Page 41
EXCEPTION HANDLING PROGRAMS
Java Program to Handle the Exception Using Try and Multiple Catch Block
This is a Java program to handle the Exception using Try and Multiple Catch Block.
A Java exception is an error condition that has occurred in a piece of code
on violation of some rules.
Java Exception Handling is managed via five keywords: try, catch, throw,
throws, and finally.
Here is the source code of the Java Program to Handle the Exception Using Try
and Multiple Catch Block. The Java program is successfully compiled and run on a
Windows system.
Page 42
* throws FileNotFoundException which is a checked
* exception*/
fis = new FileInputStream("B:/myfile.txt");
int k;
/*Method read() of FileInputStream class also throws
* a checked exception: IOException*/
while(( k = fis.read() ) != -1)
{
System.out.print((char)k);
}
/*The method close() closes the file input stream
* It throws IOException*/
fis.close();
}
catch(IndexOutOfBoundsException e)
{
System.out.println(e);
}
catch(NullPointerException e)
{
System.out.println(e);
}
catch(ArithmeticException e)
{
System.out.println(e);
}
catch(Exception e)
{
System.out.println(e);
}
}
}
Output:
$ javac Try_Catch.java
$ java Try_Catch
Page 43
Enter a:4
Enter b:5
Enter c:6
0
4
java.io.FileNotFoundException: B:/myfile.txt (No such file or directory)
Java Program to Handle the User Defined Exception using Throw Keyword
This is a Java Program to Handle the User Defined Exception Using Throw Keyword.A
part from existing Exceptions in java, we can create our own Exceptions (User defined
exceptions in java)
Here is the source code of the Java Program to Handle the User Defined Exception Using
Throw Keyword. The Java program is successfully compiled and run on a Windows
system. The program output is also shown below.
import java.util.Scanner;
class NegativeAmtException extends Exception
{
String msg;
NegativeAmtException(String msg)
{
this.msg=msg;
}
public String toString()
{
return msg;
}
}
public class User_Defined_Exception
{
public static void main(String[] args)
{
Scanner s=new Scanner(System.in);
System.out.print("Enter Amount:");
Page 44
int a=s.nextInt();
try
{
if(a<0)
{
throw new NegativeAmtException("Invalid Amount");
}
System.out.println("Amount Deposited");
}
catch(NegativeAmtException e)
{
System.out.println(e);
}
}
}
Output:
$ javac User_Defined_Exception.java
$ java User_Defined_Exception
Enter Amount:-5
Invalid Amount
Page 45
4. USER DEFINED EXCEPTION HANDLING
• User-defined exceptions provide the flexibility to customize the exception as per
our use case.
• A custom exception class must extend Exception class from java. lang package.
• Error message of a custom exception can be configured by passing message to
super class constructor, or by overriding the toString() method.
• Creating our own Exception is known as a custom exception or user-defined exception.
• Basically, Java custom exceptions are used to customize the exception according
to user needs.
• In simple words, we can say that a User-Defined Exception or custom exception
is creating your own exception class and throwing that exception using the
‘throw’ keyword.
Example: We pass the string to the constructor of the superclass- Exception which is obtained
using the “getMessage()” function on the object created.
Page 46
// Call constructor of parent Exception
super(s);
}
}
Output
Caught
• In the above code, the constructor of MyException requires a string as its argument.
• The string is passed to the parent class Exception’s constructor using super().
• The constructor of the Exception class can also be called without a parameter and
the call to super is not mandatory.
Page 47
class MyException extends Exception {
}
Output
Caught
null
• xception class.
PROGRAM:
import java.util.Scanner;
import java.io.*;
Page 48
public class Demo{
public static void main(String args[])
{ try {
int ch;
System.out.println("enter\n1.arithmeticexception\n2.arrayindexOfBoundexception\n3.Nullpoi
nterexception\n4.NumberFormtexception \n enter your choice:\n");
Scanner in=new Scanner(System.in);
ch=in.nextInt();
switch(ch)
{
case 1:
int a;
a=args.length;
System.out.println("a"+a);
int b=42/a;
break;
case 2:
int c[]={1};
c[42]=99;
break;
case 3:
String s=null;
System.out.println(s.length());
break;
case 4:
String ab;
ab= "abc";
int i=Integer.parseInt(ab);
break;
default:
System.out.println("enter vaild input....");
}
}
catch(ArithmeticException e)
{
System.out.println("divide by zero:"+e);
Page 49
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("array index oob:"+e);
}
catch(NullPointerException e)
{
System.out.println("Null pointer exception"+e);
}
catch(NumberFormatException e)
{
System.out.println("Number Formt exception"+e);
}
}
}
output:
enter
1.arithmeticexception
2.arrayindexOfBoundexception
3.Nullpointerexception
4.NumberFormtexception
enter your choice:
1
a0
enter
1.arithmeticexception
2.arrayindexOfBoundexception
3.Nullpointerexception
4.NumberFormtexception
enter your choice:
Page 50
enter
1.arithmeticexception
2.arrayindexOfBoundexception
3.Nullpointerexception
4.NumberFormtexception
enter your choice:
enter
1.arithmeticexception
2.arrayindexOfBoundexception
3.Nullpointerexception
4.NumberFormtexception
enter your choice:
***********************
Page 51