0% found this document useful (0 votes)
2 views51 pages

unit III

This document provides an overview of Exception Handling and Multithreading in Java, detailing key concepts such as exception definitions, handling mechanisms, and the differences between errors and exceptions. It outlines the use of keywords like try, catch, throw, and finally, along with examples of checked and unchecked exceptions. Additionally, it discusses the importance of managing exceptions to maintain the normal flow of a program and includes a syllabus for the related course unit.

Uploaded by

gokilam.cse
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views51 pages

unit III

This document provides an overview of Exception Handling and Multithreading in Java, detailing key concepts such as exception definitions, handling mechanisms, and the differences between errors and exceptions. It outlines the use of keywords like try, catch, throw, and finally, along with examples of checked and unchecked exceptions. Additionally, it discusses the importance of managing exceptions to maintain the normal flow of a program and includes a syllabus for the related course unit.

Uploaded by

gokilam.cse
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 51

DEPARTMENT OF CSE

R2023 - SEMESTER III


23CS301 – OBJECT ORIENTED
PROGRAMMING

UNIT III - EXCEPTION HANDLING


AND MULTITHREADING

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 HANDLING BASICS

What is an Exception in java?


Definition: Exception
• An exception is an event, which occurs during the execution of a program, that
disrupts the normal flow of the program's instructions.
• An exception is an event that occurs during the execution of a program that disrupts
the normal flow of instructions.

• Exceptions are conditions within the code.


The Java programming language uses exceptions to provide error-handling capabilities for
its programs.
• A developer can handle such conditions and take necessary corrective actions.
• Exceptions are the unwanted errors or bugs or events that restrict the normal
execution of a program.
• One of the powerful mechanism to handle the runtime errors so that the normal flow of
the application can be maintained.
• When an error occurs within a method, the method creates an object and hands it off
to the runtime system.
• Each time an exception occurs, program execution gets disrupted.
• An error message is displayed on the screen.
• It enables developers to manage the runtime errors caused by the exceptions.

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.

Here's the syntax of try...catch block:

try {
// code
}
catch(Exception e) {
// code
}

finally {
// finally block always executes
}

Key notes on exception syntax:


• When we have place the code that might generate an exception inside the try
block. Every try block is followed by a catch block.
• When an exception occurs, it is caught by the catch block.
• The catch block cannot be used without the try block.
• If an exception occurs, the finally block is executed after the try...catch
block. Otherwise, it is executed after the try block.
• For each try block, there can be only one finally block.
• It is a good practice to use the finally block. It is because it can include important
cleanup codes like,
i) code that might be accidentally skipped by return, continue or break
ii) closing a file or connection

Page 5
Example:

//expExample.java – An arithmetic exception handler because of Division by zero


class expExample {
public static void main(String[] args)

{ try {

// code that generate exception


int divideByZero = 5 / 0;
System.out.println("Rest of code in try block");
}
catch (ArithmeticException e)
{ System.out.println("ArithmeticException => " + e.getMessage());
}
finally {
System.out.println("This is the finally block");
}
}

Output

ArithmeticException => / by zero


This is the finally block

Tracing Exception handler code:


• In the example, we are trying to divide a number by 0. Here, this code generates
an exception.
• To handle the exception, we have put the code, 5 / 0 inside the try block. Now when
an exception occurs, the rest of the code inside the try block is skipped.
• The catch block catches the exception and statements inside the catch block
are executed.
• If none of the statements in the try block generates an exception, the catch block
is skipped.
• The exception is caught by the catch block. And, then the finally block is executed.

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)

Tracing out the above java code:


• When the Java run-time system detects the attempt to divide by zero, it constructs
a new exception object and then throws this exception.
• This causes the execution of Exc0 to stop, because once an exception has been
thrown, it must be caught by an exception handler and dealt with immediately
• Any exception that is not caught by your program will ultimately be processed by
the default handler.
• 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.

Reasons for Exception:


There are several reasons behind the occurrence of exceptions.
These are some conditions where an exception occurs:
• Whenever a user provides invalid data.
• The file requested to be accessed does not exist in the system.
• When the Java Virtual Machine (JVM) runs out of memory.
• Network drops in the middle of communication.

Difference between error and exception

Error Vs Exception in Java

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.

Ex: Exception in thread "main" java.lang.ArithmeticException: / by zero at


ExceptionDemo.main(ExceptionDemo.java:5)

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.

Key words used in Exception handling


There are 5 keywords used in java exception handling.
1. try A try/catch block is placed around the code that might generate an
exception. Code within a try/catch block is referred to as protected code.

2. catch A catch statement involves declaring the type of exception we are trying
to catch.

3. finally A finally block of code always executes, irrespective of occurrence of


an Exception.

4. throw It is used to execute important code such as closing connection,


stream etc. throw is used to invoke an exception explicitly.
5. throws throws is used to postpone the handling of a checked exception.

Syntax : //Example-predefined Exception – for


try //ArrayindexoutofBounds Exception
{
public class ExcepTest
//Protected code
{
} public static void main(String args[])
{
int a[] = new int[2];

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

//The finally block always Exception thrown


:java.lang.ArrayIndexOutOfBoundsException:3
executes. First element value: 6
} The finally statement is executed
Note : here array size is 2 but we are trying to access 3rd element.

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;

/* FileInputStream(File filename) is a constructor that will throw


* FileNotFoundException (a checked exception)
*/

input1 = new FileInputStream("D:/file.txt");


int m;

// The read() of FileInputStream will also throw a checked exception


while(( m = input1.read() ) != -1) {
System.out.print((char)m);
}

Page 15
// The close() will close the file input stream, and it will also throw a exception
input1.close();
}
}

Output:

Exception in thread "main" java.lang.Error: Unresolved compilation problems:


Unhandled exception type FileNotFoundException
Unhandled exception type IOException
Unhandled exception type IOException

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:

// Exception handling using Java throw for division by zero exception


class expDivisionbyzero {
public static void divideByZero() {

// throw an exception
throw new ArithmeticException("Trying to divide by 0");
}

public static void main(String[] args) {


divideByZero();
}

Page 16
}

Output

Exception in thread "main" java.lang.ArithmeticException: Trying to divide by 0


at Main.divideByZero(Main.java:5)
at Main.main(Main.java:9)

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.

Java throws keyword


throws keyword is used to declare the type of exceptions that might occur within the
method. It is used in the method declaration.

Example: Java throws keyword

// 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);
}

public static void main(String[] args)


{ try {
findFile();
}
catch (IOException e) {
System.out.println(e);
}
}
}

Output

java.io.FileNotFoundException: test.txt (The system cannot find the file specified)


When we run this program, if the file test.txt does not exist, FileInputStream throws a
FileNotFoundException which extends the IOException class.

• The findFile() method specifies that an IOException can be thrown.


The main() method calls this method and handles the exception if it is thrown.
• If a method does not handle exceptions, the type of exceptions that may occur within
it must be specified in the throws clause.

i) IOException
• This type of exception occurs while using file I/O stream operations.

For example, consider the following code snippet:

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));

while ((curline = br1.readLine()) != null) {


System.out.println(curline);
}
} catch (IOException e) {
System.err.println("IOException found :" + e.getMessage());
} finally
{ try {
if (br1 != null)
br1.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

Output: This code will generate an IOException.

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:

public void setClientInfo(String sname, String svalue) throws SQLClientInfoException


{ try {
checkClosed();
((java.sql.Connection) this.mc).setClientInfo(sname, svalue);
} catch (SQLException sqlEx) {

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:

public class sample_ClassNotFoundException {


private static final String CLASS_TO_LOAD = "main.java.Utils";

public static void main(String[] args)


{ try {
Class loadedClass = Class.forName(CLASS_TO_LOAD);
System.out.println("Class " + loadedClass + " found!");
} catch (ClassNotFoundException ex)
{ System.err.println("ClassNotFoundException was found: " +
ex.getMessage()); ex.printStackTrace();
}
}
}
Output: This code will generate a ClassNotFoundException.

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.

For example, consider the following code snippet:

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;
}

public static void main(String... args)


{ try {
Class<?> c1 = Class.forName("main.samplejava. Example");
Object t1 = c1.newInstance();
Method[] declared_Methods = c1.getDeclaredMethods();
for (Method method : declared_Methods) {
String methodName = method.getName();
if (methodName.contains("main"))
continue;

System.out.format("Invoking %s()%n", methodName);

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:

Enter your age in Numbers: 21


You can view the page
Output 2:

Enter your age in Numbers: Twelve


Exception in thread “main” java.util.InputMismatchException
at java.util.Scanner.throwFor (Unknown Source)
at java.util.Scanner.next (Unknown Source)
at java.util.Scanner.nextInt (Unknown Source)
at java.util.Scanner.nextInt (Unknown Source)
at exceptiondemo.sample_runtimedemo.main(Sample_RunTimeExceptionDemo.java:11)
Now, let us learn about other unchecked exceptions. Some of them are:

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.

For example, consider the following code snippet:

// Program to demonstrate the ArrayIndexOutOfBoundException


class sample_ArrayIndexOutOfBound {
public static void main(String args[])
{ try {
int b[] = new int[6];
b[8] = 2; // we are trying to access 9th element in an array of size 7
} catch(ArrayIndexOutOfBoundsException e)
{ System.out.println ("The array index is out of bound");
}
}
}
Output: The array index is out of bound

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.

Consider the following code snippet to demonstrate this type of exception:

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!");

return par + File.separator + f_name;


}

public static void main(String[] args) {


// This command will be successfully executed.
system.out.println(IllegalArgumentExceptionExample.createRelativePath("dir1",
"file1"));
system.out.println();

// This command will throw an IllegalArgumentException.


System.out.println(IllegalArgumentExceptionExample.createRelativePath(null,
"file1"));
}
}

Output: This code will generate an IllegalArgumentException.

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.

If a publication date already exists in the system, then it will produce an


IllegalStateException that indicates that the book cannot be published again.

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:

// Program to demonstrate the NumberFormatException


class Sample_NumberFormat {
public static void main(String args[])
{ try {
// "Test" is not a number
int n = Integer.parseInt ("Test") ;
System.out.println(n);
} catch(NumberFormatException e) {

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:

// Program to demonstrate the ArithmeticException


class Sample_ArithmeticException {
public static void main(String args[])
{ try {
int p = 30, q = 0;
int r = p/q; // It cannot be divided by zero
System.out.println ("Result = " + r);
} catch(ArithmeticException e) {
System.out.println ("Number cannot be divided by 0");
}
}
}

Output: This code will generate an ArithmeticException.

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.");
}
}

This program generates the following output:


Division by zero.

After catch statement.


The call to println( ) inside the try block is never executed. Once an exception is thrown,
program control transfers out of the try block into the catch block.

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.

The following example traps two different exception types:


// Demonstrate multiple catch statements.
class MultiCatch {
public static void main(String args[]) { try {
int a = args.length; System.out.println("a = " + a); int b = 42 / a;
int c[] = { 1 }; c[42] = 99;
} catch(ArithmeticException e) { System.out.println("Divide by 0: " + e);
} catch(ArrayIndexOutOfBoundsException e) { System.out.println("Array index oob: " +
e);
}
System.out.println("After try/catch blocks.");
}
}

Here is the output generated by running it both ways:


C:\>java MultiCatch a = 0
Divide by 0: java.lang.ArithmeticException: / by zero After try/catch blocks. C:\
>java MultiCatch TestArg a = 1
Array index oob: java.lang.ArrayIndexOutOfBoundsException:42 After try/catch blocks.

Nested try Statements


• The try statement can be nested. That is, a try statement can be inside the block
of another try.
• Each time a try statement is entered, the context of that exception is pushed on
the stack.

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.

3. NESTED TRY STATEMENTS


• In Java, using a try block inside another try block is permitted.
• It is called as nested try block.
• Every statement that we enter a statement in try block, context of that exception
is pushed onto the stack.

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[42] = 99; // generate an out-of-bounds exception


}
} catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Array index out-of-bounds: " + e);
}
} catch(ArithmeticException e) {
Page 33
Page 34
System.out.println("Divide by 0: " + e);
}
}
}

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;

Here, ThrowableInstance must be an object of type Throwable or a subclass of Throwable.


• Primitive types, such as int or char, as well as non-Throwable classes, such as String
and Object, cannot be used as exceptions.
• There are two ways you can obtain a Throwable object: using a parameter in a
catch clause, or creating one with the new operator.
• The flow of execution stops immediately after the throw statement; any
subsequent statements are not executed.
• The nearest enclosing try block is inspected to see if it has a catch statement
that matches the type of exception.
• If it does find a match, control is transferred to that statement. If not, then the
next enclosing try statement is inspected, and so on.
• If no matching catch is found, then the default exception handler halts the program
and prints the stack trace

// Demonstrate throw. class ThrowDemo { static void demoproc() { try


{ throw new NullPointerException("demo");

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);
}
}
}

Here is the resulting output:


Caught inside demoproc.
Recaught: java.lang.NullPointerException: demo

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:

type method-name(parameter-list) throws exception-list


{
// body of method
}

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.

// Demonstrate finally. class FinallyDemo {


// Through an exception out of the method. static void procA()
{ try {
System.out.println("inside procA"); throw new RuntimeException("demo");
} finally {

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

1) Checked exceptions −A checked exception is an exception that occurs at the


compiletime, these are also called as compile time exceptions. These exceptions cannot
simply be ignored at the time of compilation, the programmer should take care of
(handle) these 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.

3) Common scenarios where exceptions may occur:


There are given some scenarios where unchecked exceptions can occur.

They are as follows:


1) Scenario where ArithmeticException occurs
If we divide any number by zero, there occurs an ArithmeticException. int
a=50/0;//ArithmeticException

2) Scenario where NullPointerException occurs


If we have null value in any variable, performing any operation by the variable occurs an
NullPointerException.
String s=null; System.out.println(s.length());//NullPointerException

3) Scenario where ArrayIndexOutOfBoundsException occurs


If you are inserting any value in the wrongindex, it would result
ArrayIndexOutOfBoundsException as shown below:
int a[]=new int[5];
a[10]=50; //ArrayIndexOutOfBoundsException

3. Java’s Built-in Exceptions


There are two types of exceptions
a) Java’s Built-in Exceptions
b) User-defined Exceptions

All exceptions must be a child of Throwable.


If we want to write a checked exception that is automatically enforced by the Handle ,we
need to extend the Exception class.

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.

class MyOwnException extends Exception


{
Public MyOwnException(String msg) { super(msg);
}
}
class EmployeeTest
{
Static void employeeAge(int age) throws
MyOwnException { if(age < 0)
throw new MyOwnException("Age can't be less than zero"); else
System.out.println("Input is valid!!");
}
public static void main(String[] args)
{
try { employeeAge(-2);
}
catch (MyOwnException e)
{
e.printStackTrace();
}
}
}

Advantages of Exception Handling


• Exception handling allows us to control the normal flow of the program by
using exception handling in program.
• It throws an exception whenever a calling method encounters an error providing that
the calling method takes care of that error.
• It also gives us the scope of organizing and differentiating between different error
types using a separate block of codes. This is done with the help of try-catch blocks.

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.

The program output is also shown below.


import java.io.FileInputStream;
import java.util.Scanner;

public class Try_Catch


{
public static void main(String[] args)
{
int a=5,b=0,c,d,f;
try
{
Scanner s=new Scanner(System.in);
System.out.print("Enter a:");
a=s.nextInt();
System.out.print("Enter b:");
b=s.nextInt();
System.out.print("Enter c:");
c=s.nextInt();
d=a/b;
System.out.println(d); f=a
%c; System.out.println(f);
FileInputStream fis = null;
/*This constructor FileInputStream(File filename)

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.

Why use custom or user defined exceptions?


• Java exceptions cover almost all the general types of exceptions that may occur in
the programming. However, we sometimes need to create custom exceptions.
• Following are a few of the reasons to use custom exceptions:
• To catch and provide specific treatment to a subset of existing Java exceptions.
• Business logic exceptions: These are the exceptions related to business logic and
workflow. It is useful for the application users or the developers to understand the
exact problem.
• In order to create a custom exception, we need to extend the Exception class
that belongs to java.lang package.

Example: We pass the string to the constructor of the superclass- Exception which is obtained
using the “getMessage()” function on the object created.

// A Class that represents use-defined exception

class MyException extends Exception {


public MyException(String s)
{

Page 46
// Call constructor of parent Exception
super(s);
}
}

// A Class that uses above MyException


public class Main {
// Driver Program
public static void main(String args[])
{
try {
// Throw an object of user defined exception
throw new MyException("User Defined Exception ");
}
catch (MyException ex) {
System.out.println("Caught");

// Print the message from MyException object


System.out.println(ex.getMessage());
}
}
}

Output
Caught

User Defined Exception Code

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

// A Class that represents use-defined exception

Page 47
class MyException extends Exception {
}

// A Class that uses above MyException


public class setText {
// Driver Program
public static void main(String args[])
{
try {
// Throw an object of user defined exception
throw new MyException();
}
catch (MyException ex) {
System.out.println("Caught");
System.out.println(ex.getMessage());
}
}
}

Output
Caught
null

• xception class.

USER DEFINED EXCEPTION HANDLING CODE

Create a java program to demonstrate user defined exception.

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

divide by zero:java.lang.ArithmeticException: / by zero

enter
1.arithmeticexception
2.arrayindexOfBoundexception
3.Nullpointerexception
4.NumberFormtexception
enter your choice:

array index oob:java.lang.ArrayIndexOutOfBoundsException: 42

Page 50
enter
1.arithmeticexception
2.arrayindexOfBoundexception
3.Nullpointerexception
4.NumberFormtexception
enter your choice:

Null pointer exceptionjava.lang.NullPointerException

enter
1.arithmeticexception
2.arrayindexOfBoundexception
3.Nullpointerexception
4.NumberFormtexception
enter your choice:

Number Formt exceptionjava.lang.NumberFormatException: For input string: "abc"

***********************

Page 51

You might also like