SlideShare a Scribd company logo
1 of 46
Download to read offline
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 1
DEPARTMENT OF INFORMATION TECHNOLOGY
R2017 - SEMESTER III
CS3391 – OBJECT ORIENTED PROGRAMMING
UNIT III - EXCEPTION HANDLING
AND MULTITHREADING
CLASS NOTES
Complimented with
PERSONALIZED LEARNING MATERIAL (PLM)
With
PERSONALIZED ASSESSMENT TESTS (PATs)
PERSONALIZED LEARNING MATERIAL (PLM)
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 2
An Introduction to PLM
The PERSONALIZED LEARNING MATERIAL (PLM) is special Type of Learning Material
designed and developed by Er. K.Khaja Mohideen , Assistant Professor , Aalim Muhammed
Salegh College of Engineering, Avadi-IAF, Chennai – 600 055, India.
This material called PLM is an innovative Learning Type based Artificial Intelligence
based Suggestive learning Strategy (SLS) that recommends the selective Topics to Learners
of different Learning mind sets groups.
We identified three major such Learner Groups from Subject Learning Student
Communities and are as follows:
1) Smart Learning Groups
2) Effective Learning Groups
3) Slow Learning Groups
The three Coloring depicts the following levels of Experiencing Learners groups:
1) Smart Learning Groups – Greenish Shadow
2) Effective Learning Groups – Orange Shadow
3) Slow Learning Groups – Red Shadow
The following picture illustrates the same:
Note: The decision on PLM Topic grouping type is based on the Designer’s Academic
Experience and his Academic Excellence on the selective Course Domain.
MOST IMPORTANT IMPORTANT NOT IMPORTANT
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 3
PERSONALIZED ASSESSMENT TESTS (PATs)
An Introduction to PAT
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 4
INDEX
UNIT III - EXCEPTION HANDLING AND
MULTITHREADING
SL NO TOPIC PAGE NO.
UNIT – III : Syllabus with PL 02
1 EXCEPTION HANDLING BASICS 06
2 MULTIPLE CATCH CLAUSES 29
3 NESTED TRY STATEMENTS 30
4 JAVA’S BUILT-IN EXCEPTIONS 35
5 USER DEFINED EXCEPTION 41
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
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 5
UNIT – II : Syllabus with PL
SYLLABUS:
UNIT III EXCEPTION HANDLING AND MULTITHREADING 9
Exception Handling basics – Multiple catch Clauses – Nested try Statements – Java’s
Built-in Exceptions – User defined Exception.
Multithreaded Programming: Java Thread Model–Creating a Thread and Multiple
Threads – Priorities – Synchronization – Inter Thread Communication- Suspending –
Resuming, and Stopping Threads –Multithreading.
Wrappers
Auto boxing.
TOTAL TOPICS: 15
NOTE:
 Important Topic
 Less Important
  Not Important
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 6
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.
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 7
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
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 8
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.
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 9
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
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 10
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
The error implies a problem that mostly
arises due to the shortage of system
resources.
On the other hand, the exceptions occur
during runtime and compile time.
Errors indicate serious problems and
abnormal conditions that most applications
should not try to handle.
Exception Handling is a mechanism to handle
runtime errors.
Error defines problems that are not
expected to be caught under normal
circumstances by our program.
An exception normally disrupts the normal
flow of the application; that is why we need
to handle exceptions.
For example memory error, hardware error,
JVM error etc.
Example: ClassNotFoundException,
IOException, SQLException,
RemoteException, etc.
Types of Exceptions
• The parent class of all the exception classes is the java.lang.Exception class.
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 11
• 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
Why Exceptions?
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 12
 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];
catch(ExceptionType1 e1)
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology 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.
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology 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);
}
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology 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();
}
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology 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.
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology 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 {
// declareing the type of exception
public static void findFile() throws IOException {
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 18
// 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:UserguestDesktopFile2.txt";
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 19
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) {
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 20
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
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 21
 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!");
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 22
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
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 23
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:
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 24
// 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
a method. For example, if a method is defined with non-empty string as parameters. But
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 25
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.
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 26
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) {
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 27
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.
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 28
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.
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 29
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.
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 30
• 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) {
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 31
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");
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 32
} 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 {
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 33
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 {
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 34
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.
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 35
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.
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 36
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.
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 37
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)
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 38
* 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
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 39
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:");
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 40
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
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 41
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)
{
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 42
// 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
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 43
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.*;
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 44
public class Demo{
public static void main(String args[]){
try {
int ch;
System.out.println("entern1.arithmeticexceptionn2.arrayindexOfBoundexceptionn3.Nullpoi
nterexceptionn4.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);
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 45
}
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:
2
array index oob:java.lang.ArrayIndexOutOfBoundsException: 42
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 46
enter
1.arithmeticexception
2.arrayindexOfBoundexception
3.Nullpointerexception
4.NumberFormtexception
enter your choice:
3
Null pointer exceptionjava.lang.NullPointerException
enter
1.arithmeticexception
2.arrayindexOfBoundexception
3.Nullpointerexception
4.NumberFormtexception
enter your choice:
4
Number Formt exceptionjava.lang.NumberFormatException: For input string: "abc"
***********************

More Related Content

What's hot

What's hot (20)

Python-DataAbstarction.pptx
Python-DataAbstarction.pptxPython-DataAbstarction.pptx
Python-DataAbstarction.pptx
 
Oop java
Oop javaOop java
Oop java
 
CS3391 OOP UT-I T3 FEATURES OF OBJECT ORIENTED PROGRAMMING
CS3391 OOP UT-I T3 FEATURES OF OBJECT ORIENTED PROGRAMMINGCS3391 OOP UT-I T3 FEATURES OF OBJECT ORIENTED PROGRAMMING
CS3391 OOP UT-I T3 FEATURES OF OBJECT ORIENTED PROGRAMMING
 
Java I/o streams
Java I/o streamsJava I/o streams
Java I/o streams
 
1 .java basic
1 .java basic1 .java basic
1 .java basic
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
 
Core java complete ppt(note)
Core java  complete  ppt(note)Core java  complete  ppt(note)
Core java complete ppt(note)
 
String classes and its methods.20
String classes and its methods.20String classes and its methods.20
String classes and its methods.20
 
14 file handling
14 file handling14 file handling
14 file handling
 
stack presentation
stack presentationstack presentation
stack presentation
 
Control Statements in Java
Control Statements in JavaControl Statements in Java
Control Statements in Java
 
Core java concepts
Core java  conceptsCore java  concepts
Core java concepts
 
Java interfaces
Java interfacesJava interfaces
Java interfaces
 
Constructor in java
Constructor in javaConstructor in java
Constructor in java
 
String and string buffer
String and string bufferString and string buffer
String and string buffer
 
Java Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and StreamsJava Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and Streams
 
Polymorphism presentation in java
Polymorphism presentation in javaPolymorphism presentation in java
Polymorphism presentation in java
 
Interfaces in java
Interfaces in javaInterfaces in java
Interfaces in java
 
Collection framework
Collection frameworkCollection framework
Collection framework
 
Abstraction java
Abstraction javaAbstraction java
Abstraction java
 

Similar to CS3391 -OOP -UNIT – III NOTES FINAL.pdf

UNIT-3.pptx Exception Handling and Multithreading
UNIT-3.pptx Exception Handling and MultithreadingUNIT-3.pptx Exception Handling and Multithreading
UNIT-3.pptx Exception Handling and MultithreadingSakkaravarthiS1
 
UNIT III 2021R.pptx
UNIT III 2021R.pptxUNIT III 2021R.pptx
UNIT III 2021R.pptxRDeepa9
 
UNIT III 2021R.pptx
UNIT III 2021R.pptxUNIT III 2021R.pptx
UNIT III 2021R.pptxRDeepa9
 
Java Exceptions and Exception Handling
 Java  Exceptions and Exception Handling Java  Exceptions and Exception Handling
Java Exceptions and Exception HandlingMaqdamYasir
 
Chapter 5 Exception Handling (1).pdf
Chapter 5 Exception Handling (1).pdfChapter 5 Exception Handling (1).pdf
Chapter 5 Exception Handling (1).pdfFacultyAnupamaAlagan
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in javaKavitha713564
 
Java Exception Handling
Java Exception HandlingJava Exception Handling
Java Exception HandlingGovindanS3
 
Ch-1_5.pdf this is java tutorials for all
Ch-1_5.pdf this is java tutorials for allCh-1_5.pdf this is java tutorials for all
Ch-1_5.pdf this is java tutorials for allHayomeTakele
 
Lecture 1 Try Throw Catch.pptx
Lecture 1 Try Throw Catch.pptxLecture 1 Try Throw Catch.pptx
Lecture 1 Try Throw Catch.pptxVishuSaini22
 
Exception handling2.0.pptx
Exception handling2.0.pptxException handling2.0.pptx
Exception handling2.0.pptxSelvakumarNSNS
 
Java -Exception handlingunit-iv
Java -Exception handlingunit-ivJava -Exception handlingunit-iv
Java -Exception handlingunit-ivRubaNagarajan
 
Exception handling in Java
Exception handling in JavaException handling in Java
Exception handling in JavaAnkit Rai
 
Exceptions overview
Exceptions overviewExceptions overview
Exceptions overviewBharath K
 
Introduction to java exceptions
Introduction to java exceptionsIntroduction to java exceptions
Introduction to java exceptionsSujit Kumar
 

Similar to CS3391 -OOP -UNIT – III NOTES FINAL.pdf (20)

Exception
ExceptionException
Exception
 
UNIT-3.pptx Exception Handling and Multithreading
UNIT-3.pptx Exception Handling and MultithreadingUNIT-3.pptx Exception Handling and Multithreading
UNIT-3.pptx Exception Handling and Multithreading
 
UNIT III 2021R.pptx
UNIT III 2021R.pptxUNIT III 2021R.pptx
UNIT III 2021R.pptx
 
UNIT III 2021R.pptx
UNIT III 2021R.pptxUNIT III 2021R.pptx
UNIT III 2021R.pptx
 
Java Exceptions and Exception Handling
 Java  Exceptions and Exception Handling Java  Exceptions and Exception Handling
Java Exceptions and Exception Handling
 
Chapter 5 Exception Handling (1).pdf
Chapter 5 Exception Handling (1).pdfChapter 5 Exception Handling (1).pdf
Chapter 5 Exception Handling (1).pdf
 
Exception handling in java
Exception handling  in javaException handling  in java
Exception handling in java
 
Exception handling in .net
Exception handling in .netException handling in .net
Exception handling in .net
 
Exception handling in ASP .NET
Exception handling in ASP .NETException handling in ASP .NET
Exception handling in ASP .NET
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
JAVA PPT -4 BY ADI.pdf
JAVA PPT -4 BY ADI.pdfJAVA PPT -4 BY ADI.pdf
JAVA PPT -4 BY ADI.pdf
 
Java Exception Handling
Java Exception HandlingJava Exception Handling
Java Exception Handling
 
Ch-1_5.pdf this is java tutorials for all
Ch-1_5.pdf this is java tutorials for allCh-1_5.pdf this is java tutorials for all
Ch-1_5.pdf this is java tutorials for all
 
Lecture 1 Try Throw Catch.pptx
Lecture 1 Try Throw Catch.pptxLecture 1 Try Throw Catch.pptx
Lecture 1 Try Throw Catch.pptx
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
 
Exception handling2.0.pptx
Exception handling2.0.pptxException handling2.0.pptx
Exception handling2.0.pptx
 
Java -Exception handlingunit-iv
Java -Exception handlingunit-ivJava -Exception handlingunit-iv
Java -Exception handlingunit-iv
 
Exception handling in Java
Exception handling in JavaException handling in Java
Exception handling in Java
 
Exceptions overview
Exceptions overviewExceptions overview
Exceptions overview
 
Introduction to java exceptions
Introduction to java exceptionsIntroduction to java exceptions
Introduction to java exceptions
 

More from AALIM MUHAMMED SALEGH COLLEGE OF ENGINEERING

More from AALIM MUHAMMED SALEGH COLLEGE OF ENGINEERING (20)

JAVA PROGRAM CONSTRUCTS OR LANGUAGE BASICS.pptx
JAVA PROGRAM CONSTRUCTS OR LANGUAGE BASICS.pptxJAVA PROGRAM CONSTRUCTS OR LANGUAGE BASICS.pptx
JAVA PROGRAM CONSTRUCTS OR LANGUAGE BASICS.pptx
 
INTRO TO PROGRAMMING.ppt
INTRO TO PROGRAMMING.pptINTRO TO PROGRAMMING.ppt
INTRO TO PROGRAMMING.ppt
 
CS3391 OOP UT-I T4 JAVA BUZZWORDS.pptx
CS3391 OOP UT-I T4 JAVA BUZZWORDS.pptxCS3391 OOP UT-I T4 JAVA BUZZWORDS.pptx
CS3391 OOP UT-I T4 JAVA BUZZWORDS.pptx
 
CS3391 OOP UT-I T1 OVERVIEW OF OOP
CS3391 OOP UT-I T1 OVERVIEW OF OOPCS3391 OOP UT-I T1 OVERVIEW OF OOP
CS3391 OOP UT-I T1 OVERVIEW OF OOP
 
CS3391 OOP UT-I T2 OBJECT ORIENTED PROGRAMMING PARADIGM.pptx
CS3391 OOP UT-I T2 OBJECT ORIENTED PROGRAMMING PARADIGM.pptxCS3391 OOP UT-I T2 OBJECT ORIENTED PROGRAMMING PARADIGM.pptx
CS3391 OOP UT-I T2 OBJECT ORIENTED PROGRAMMING PARADIGM.pptx
 
CS3391 -OOP -UNIT – V NOTES FINAL.pdf
CS3391 -OOP -UNIT – V NOTES FINAL.pdfCS3391 -OOP -UNIT – V NOTES FINAL.pdf
CS3391 -OOP -UNIT – V NOTES FINAL.pdf
 
CS3391 -OOP -UNIT – IV NOTES FINAL.pdf
CS3391 -OOP -UNIT – IV NOTES FINAL.pdfCS3391 -OOP -UNIT – IV NOTES FINAL.pdf
CS3391 -OOP -UNIT – IV NOTES FINAL.pdf
 
CS3251-_PIC
CS3251-_PICCS3251-_PIC
CS3251-_PIC
 
CS8080 information retrieval techniques unit iii ppt in pdf
CS8080 information retrieval techniques unit iii ppt in pdfCS8080 information retrieval techniques unit iii ppt in pdf
CS8080 information retrieval techniques unit iii ppt in pdf
 
CS8080 IRT UNIT I NOTES.pdf
CS8080 IRT UNIT I  NOTES.pdfCS8080 IRT UNIT I  NOTES.pdf
CS8080 IRT UNIT I NOTES.pdf
 
CS8080_IRT_UNIT - III T14 SEQUENTIAL SEARCHING.pdf
CS8080_IRT_UNIT - III T14 SEQUENTIAL SEARCHING.pdfCS8080_IRT_UNIT - III T14 SEQUENTIAL SEARCHING.pdf
CS8080_IRT_UNIT - III T14 SEQUENTIAL SEARCHING.pdf
 
CS8080_IRT_UNIT - III T15 MULTI-DIMENSIONAL INDEXING.pdf
CS8080_IRT_UNIT - III T15 MULTI-DIMENSIONAL INDEXING.pdfCS8080_IRT_UNIT - III T15 MULTI-DIMENSIONAL INDEXING.pdf
CS8080_IRT_UNIT - III T15 MULTI-DIMENSIONAL INDEXING.pdf
 
CS8080_IRT_UNIT - III T13 INVERTED INDEXES.pdf
CS8080_IRT_UNIT - III T13 INVERTED  INDEXES.pdfCS8080_IRT_UNIT - III T13 INVERTED  INDEXES.pdf
CS8080_IRT_UNIT - III T13 INVERTED INDEXES.pdf
 
CS8080 IRT UNIT - III SLIDES IN PDF.pdf
CS8080  IRT UNIT - III  SLIDES IN PDF.pdfCS8080  IRT UNIT - III  SLIDES IN PDF.pdf
CS8080 IRT UNIT - III SLIDES IN PDF.pdf
 
CS8080_IRT_UNIT - III T11 ORGANIZING THE CLASSES.pdf
CS8080_IRT_UNIT - III T11 ORGANIZING THE CLASSES.pdfCS8080_IRT_UNIT - III T11 ORGANIZING THE CLASSES.pdf
CS8080_IRT_UNIT - III T11 ORGANIZING THE CLASSES.pdf
 
CS8080_IRT_UNIT - III T12 INDEXING AND SEARCHING.pdf
CS8080_IRT_UNIT - III T12 INDEXING AND SEARCHING.pdfCS8080_IRT_UNIT - III T12 INDEXING AND SEARCHING.pdf
CS8080_IRT_UNIT - III T12 INDEXING AND SEARCHING.pdf
 
CS8080_IRT_UNIT - III T11 ORGANIZING THE CLASSES.pdf
CS8080_IRT_UNIT - III T11 ORGANIZING THE CLASSES.pdfCS8080_IRT_UNIT - III T11 ORGANIZING THE CLASSES.pdf
CS8080_IRT_UNIT - III T11 ORGANIZING THE CLASSES.pdf
 
CS8080_IRT_UNIT - III T10 ACCURACY AND ERROR.pdf
CS8080_IRT_UNIT - III T10  ACCURACY AND ERROR.pdfCS8080_IRT_UNIT - III T10  ACCURACY AND ERROR.pdf
CS8080_IRT_UNIT - III T10 ACCURACY AND ERROR.pdf
 
CS8080_IRT_UNIT - III T9 EVALUATION METRICS.pdf
CS8080_IRT_UNIT - III T9 EVALUATION METRICS.pdfCS8080_IRT_UNIT - III T9 EVALUATION METRICS.pdf
CS8080_IRT_UNIT - III T9 EVALUATION METRICS.pdf
 
CS8080_IRT_UNIT - III T8 FEATURE SELECTION OR DIMENSIONALITY REDUCTION.pdf
CS8080_IRT_UNIT - III T8  FEATURE SELECTION OR DIMENSIONALITY REDUCTION.pdfCS8080_IRT_UNIT - III T8  FEATURE SELECTION OR DIMENSIONALITY REDUCTION.pdf
CS8080_IRT_UNIT - III T8 FEATURE SELECTION OR DIMENSIONALITY REDUCTION.pdf
 

Recently uploaded

High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Dr.Costas Sachpazis
 
chaitra-1.pptx fake news detection using machine learning
chaitra-1.pptx  fake news detection using machine learningchaitra-1.pptx  fake news detection using machine learning
chaitra-1.pptx fake news detection using machine learningmisbanausheenparvam
 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCall Girls in Nagpur High Profile
 
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝soniya singh
 
microprocessor 8085 and its interfacing
microprocessor 8085  and its interfacingmicroprocessor 8085  and its interfacing
microprocessor 8085 and its interfacingjaychoudhary37
 
power system scada applications and uses
power system scada applications and usespower system scada applications and uses
power system scada applications and usesDevarapalliHaritha
 
HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2RajaP95
 
SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )Tsuyoshi Horigome
 
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...VICTOR MAESTRE RAMIREZ
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escortsranjana rawat
 
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escortsranjana rawat
 
Artificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxArtificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxbritheesh05
 
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionSachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionDr.Costas Sachpazis
 
Call Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call GirlsCall Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call Girlsssuser7cb4ff
 
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...srsj9000
 
Introduction to Microprocesso programming and interfacing.pptx
Introduction to Microprocesso programming and interfacing.pptxIntroduction to Microprocesso programming and interfacing.pptx
Introduction to Microprocesso programming and interfacing.pptxvipinkmenon1
 
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130Suhani Kapoor
 
Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AIabhishek36461
 

Recently uploaded (20)

High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
 
chaitra-1.pptx fake news detection using machine learning
chaitra-1.pptx  fake news detection using machine learningchaitra-1.pptx  fake news detection using machine learning
chaitra-1.pptx fake news detection using machine learning
 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
 
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
 
microprocessor 8085 and its interfacing
microprocessor 8085  and its interfacingmicroprocessor 8085  and its interfacing
microprocessor 8085 and its interfacing
 
power system scada applications and uses
power system scada applications and usespower system scada applications and uses
power system scada applications and uses
 
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptxExploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
 
HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2
 
SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )
 
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
 
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
 
Artificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxArtificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptx
 
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionSachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
 
Call Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call GirlsCall Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call Girls
 
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
 
Introduction to Microprocesso programming and interfacing.pptx
Introduction to Microprocesso programming and interfacing.pptxIntroduction to Microprocesso programming and interfacing.pptx
Introduction to Microprocesso programming and interfacing.pptx
 
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
 
Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AI
 

CS3391 -OOP -UNIT – III NOTES FINAL.pdf

  • 1. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 1 DEPARTMENT OF INFORMATION TECHNOLOGY R2017 - SEMESTER III CS3391 – OBJECT ORIENTED PROGRAMMING UNIT III - EXCEPTION HANDLING AND MULTITHREADING CLASS NOTES Complimented with PERSONALIZED LEARNING MATERIAL (PLM) With PERSONALIZED ASSESSMENT TESTS (PATs) PERSONALIZED LEARNING MATERIAL (PLM)
  • 2. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 2 An Introduction to PLM The PERSONALIZED LEARNING MATERIAL (PLM) is special Type of Learning Material designed and developed by Er. K.Khaja Mohideen , Assistant Professor , Aalim Muhammed Salegh College of Engineering, Avadi-IAF, Chennai – 600 055, India. This material called PLM is an innovative Learning Type based Artificial Intelligence based Suggestive learning Strategy (SLS) that recommends the selective Topics to Learners of different Learning mind sets groups. We identified three major such Learner Groups from Subject Learning Student Communities and are as follows: 1) Smart Learning Groups 2) Effective Learning Groups 3) Slow Learning Groups The three Coloring depicts the following levels of Experiencing Learners groups: 1) Smart Learning Groups – Greenish Shadow 2) Effective Learning Groups – Orange Shadow 3) Slow Learning Groups – Red Shadow The following picture illustrates the same: Note: The decision on PLM Topic grouping type is based on the Designer’s Academic Experience and his Academic Excellence on the selective Course Domain. MOST IMPORTANT IMPORTANT NOT IMPORTANT
  • 3. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 3 PERSONALIZED ASSESSMENT TESTS (PATs) An Introduction to PAT
  • 4. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 4 INDEX UNIT III - EXCEPTION HANDLING AND MULTITHREADING SL NO TOPIC PAGE NO. UNIT – III : Syllabus with PL 02 1 EXCEPTION HANDLING BASICS 06 2 MULTIPLE CATCH CLAUSES 29 3 NESTED TRY STATEMENTS 30 4 JAVA’S BUILT-IN EXCEPTIONS 35 5 USER DEFINED EXCEPTION 41 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
  • 5. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 5 UNIT – II : Syllabus with PL SYLLABUS: UNIT III EXCEPTION HANDLING AND MULTITHREADING 9 Exception Handling basics – Multiple catch Clauses – Nested try Statements – Java’s Built-in Exceptions – User defined Exception. Multithreaded Programming: Java Thread Model–Creating a Thread and Multiple Threads – Priorities – Synchronization – Inter Thread Communication- Suspending – Resuming, and Stopping Threads –Multithreading. Wrappers Auto boxing. TOTAL TOPICS: 15 NOTE:  Important Topic  Less Important   Not Important
  • 6. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 6 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.
  • 7. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 7 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
  • 8. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 8 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.
  • 9. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 9 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
  • 10. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 10 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 The error implies a problem that mostly arises due to the shortage of system resources. On the other hand, the exceptions occur during runtime and compile time. Errors indicate serious problems and abnormal conditions that most applications should not try to handle. Exception Handling is a mechanism to handle runtime errors. Error defines problems that are not expected to be caught under normal circumstances by our program. An exception normally disrupts the normal flow of the application; that is why we need to handle exceptions. For example memory error, hardware error, JVM error etc. Example: ClassNotFoundException, IOException, SQLException, RemoteException, etc. Types of Exceptions • The parent class of all the exception classes is the java.lang.Exception class.
  • 11. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 11 • 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 Why Exceptions?
  • 12. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 12  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]; catch(ExceptionType1 e1)
  • 13. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology 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.
  • 14. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology 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); }
  • 15. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology 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(); }
  • 16. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology 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.
  • 17. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology 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 { // declareing the type of exception public static void findFile() throws IOException {
  • 18. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 18 // 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:UserguestDesktopFile2.txt";
  • 19. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 19 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) {
  • 20. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 20 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
  • 21. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 21  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!");
  • 22. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 22 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
  • 23. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 23 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:
  • 24. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 24 // 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 a method. For example, if a method is defined with non-empty string as parameters. But
  • 25. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 25 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.
  • 26. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 26 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) {
  • 27. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 27 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.
  • 28. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 28 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.
  • 29. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 29 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.
  • 30. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 30 • 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) {
  • 31. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 31 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");
  • 32. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 32 } 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 {
  • 33. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 33 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 {
  • 34. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 34 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.
  • 35. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 35 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.
  • 36. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 36 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.
  • 37. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 37 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)
  • 38. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 38 * 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
  • 39. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 39 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:");
  • 40. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 40 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
  • 41. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 41 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) {
  • 42. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 42 // 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
  • 43. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 43 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.*;
  • 44. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 44 public class Demo{ public static void main(String args[]){ try { int ch; System.out.println("entern1.arithmeticexceptionn2.arrayindexOfBoundexceptionn3.Nullpoi nterexceptionn4.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);
  • 45. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 45 } 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: 2 array index oob:java.lang.ArrayIndexOutOfBoundsException: 42
  • 46. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 46 enter 1.arithmeticexception 2.arrayindexOfBoundexception 3.Nullpointerexception 4.NumberFormtexception enter your choice: 3 Null pointer exceptionjava.lang.NullPointerException enter 1.arithmeticexception 2.arrayindexOfBoundexception 3.Nullpointerexception 4.NumberFormtexception enter your choice: 4 Number Formt exceptionjava.lang.NumberFormatException: For input string: "abc" ***********************