Exception Handling
Course Code: CSC 1205 Course Title: Object Oriented Programming 1
Dept. of Computer Science
Faculty of Science and Technology
Lecturer No: Week No: Semester: Summer
Lecturer: Rahul Biswas
Lecture Outline
1. Introduction to Exception Handling
2. Exception Types
3. Common Exceptions
4. Advantages of Exception Handling
5. User Defined Exception
6. Exception Handling
Introduction to Exception
Handling
What is Exception
An exception is an abnormal condition that arises in a code sequence at run
time. In other words, an exception is a runtime error.
See the following program:
After execution:
Introduction to Exception
Handling
More about Exception
Some exceptions are caused by user error, others by programmer error, and
others by physical resources that have failed in some manner.
So, exception may occur whenever:
A user enters an invalid data. (Example: InputMismatchException,
ArithmeticException).
A file that needs to be opened cannot be found. (Example:
FileNotFoundException, ClassNotFoundException).
A network connection has been lost in the middle of communications or
the JVM has run out of memory. (Example: SocketException,
ConnectException).
Introduction to Exception
Handling
More about Exception
A Java exception is an object that describes an exceptional (that is, error)
condition that has occurred in a piece of code.
When an exceptional condition arises, an object representing that exception is
created and thrown in the method that caused the error.
Any exception which is thrown, must be caught by an exception handler.
If the programmer hasn't provided one, the exception will be caught by a
catch-all exception handler/default exception handler provided by the system.
The default exception handler may terminate the application.
Exception Types
Java Exception Types
Exception Types
Error vs Exception
Error:
An Error is a subclass of Throwable that indicates serious problems that a
reasonable application should not try to catch.
Most such errors are abnormal conditions.
Such as: virtual Machine Error, out of memory, stack overflow, thread
Death, linkage Error.
Exception:
The class Exception and its subclasses are a form of Throwable that
indicates conditions that a reasonable application might want to catch.
Such as: array index out of bounds, arithmetic errors (divide by zero), null
Pointer Exception, I/O Exceptions.
Exception Types
Checked vs Unchecked
Checked Exception (Compile Time Exception)
A checked exception is an exception that occurs at the compile time. They
are also called as compile time exceptions. These exceptions cannot
simply be ignored at the time of compilation.
If your code invokes a method which is defined to throw checked
exception, your code MUST provide a catch handler.
The compiler generates an error if the appropriate catch handler is not
present.
Checked exceptions are subclassed from Exception class.
Exception Types
Checked vs Unchecked
Unchecked Exception (Run Time Exception)
An unchecked exception is an exception that occurs at the time of
program execution. They are also called as Runtime Exceptions.
Runtime exceptions are ignored at the time of compilation.
If an unchecked exception is not caught, it will go to the default catch-all
handler for the application.
All Unchecked exceptions are subclassed from RuntimeException.
Common Exceptions
Common Exceptions
ArrayIndexOutOfBoundException:
Occurs when we try to access to an index position larger than the
maximum index value of the array index.
For example, if the size of an array is 5 then, the maximum value of index
is 4. ArrayIndexOutOfBoundException will be thrown if we try to access
an index position greater than 4.
ArithmeticException:
When we try to divide some value by 0, ArithmeticException occurs.
For example: 42/0, it will throw an ArithmeticException.
NullPointerException:
Occurs when we try work (access/use/check) on a null value.
Common Exceptions
Common Exceptions
InputMismatchException:
Occurs when an invalid input is given in a program.
For example: it occurs when we give a character as input instead of an
integer.
NumberFormatException:
Occurs when we try to convert a String to an integer or double, but the
string does not contain any numeric character.
Advantages of Exception
Handling
Advantages
Separating Error-Handling Code from "Regular" Code.
Propagating Errors Up the Call Stack.
Grouping and Differentiating Error Types.
User Defined Exception
What is User Defined Exception
Although Java’s built-in exceptions handle most common errors, but
sometimes it is necessary create our own exception. These are user defined
exception.
User Defined Exception
How to Define User Defined Exception
To define your own exception you must do the following:
Create an exception class to hold the exception data.
Your exception class must subclass "Exception" or another exception class
Note: to create unchecked exceptions, subclass the RuntimeException
class.
Minimally, your exception class should provide a constructor which takes
the exception description as its argument.
User Defined Exception
Example of User Defined Exception
User Defined Exception
Throw User Defined Exception
To throw your own exceptions:
If your exception is checked, any method which is going to throw the
exception must define it using the throws keyword
When an exceptional condition occurs, create a new instance of the
exception and throw it.
User Defined Exception
Example of How to throw User Defined Exception
Exception Handling
How Java Manage Exception Handling
Java has 5 keywords for exception handling:
try - Program statements that you want to monitor for exceptions are
contained within a try block.
catch - If an exception occurs within the try block, it is thrown. Your code
can catch this exception (using catch) and handle it in some rational
manner.
finally - Any code that absolutely must be executed after a try block
completes is put in a finally block.
throw - To manually throw an exception, use the keyword throw
throws - Any exception that is thrown out of a method must be specified
as such by a throws clause
Exception Handling
Syntax of try-catch
try {
// Code which might throw an exception
}
catch(Exception ex) {
// code to handle an exception
}
Exception Handling
Displaying a Description of an Exception
catch (ArithmeticException e) {
System.out.println("Exception: " + e);
}
Output:
Exception: java.lang.ArithmeticException: / by zero
Introduction to Exception
Handling
Syntax of Multiple Catch Clauses
try {
// Code which might throw an exception
}
catch(FileNotFoundException x) {
// code to handle a FileNotFound exception
}
catch(IOException x) {
// code to handle any other I/O exceptions
}
catch(Exception x) {
// Code to catch any other type of exception
}
Introduction to Exception
Handling
Syntax of Nested Try Statements
try {
try {
// Code which might throw an exception
}
catch(ArithmeticException ex1) {
// code to handle a ArithmeticException exception
}
}
catch(FileNotFoundException ex2) {
// code to handle a FileNotFound exception
}
Introduction to Exception
Handling
Syntax of try-catch-finally
try {
// Code which might throw an exception
}
catch(IOException x) {
// code to handle any other I/O exceptions
}
catch(Exception x) {
// Code to catch any other type of exception
}
finally {
// This code is ALWAYS executed
}
Introduction to Exception
Handling
Syntax of throw
So far, we have only been catching exceptions that are thrown by the Java run-
time system. However, it is possible for our program to throw an exception
explicitly, using the throw statement.
The general form of throw is shown here:
Introduction to Exception
Handling
Example of throw
Introduction to Exception
Handling
Syntax of throws
If a method can cause an exception that it does not handle (we have seen it in
throw example), it must specify this behavior so that callers of the method can
guard themselves against that exception.
This is the general form of a method declaration that includes a throws clause:
Introduction to Exception
Handling
Example of throws
Books
1. Java The Complete Reference- Ninth Edition by Herbert Schildt
References
• https://docs.oracle.com/javase/tutorial/