Object Oriented Programming
Exception Handling
Prepared By
Mehak Usmani
1
Objectives
1. To get an overview of exceptions and exception handling
2. To explore the advantages of using exception handling
3. To distinguish exception types: Error vs. Exception and checked vs. unchecked
4. To explain how an exception is propagated
5. To obtain information from an exception object
6. To write a try-catch block to handle exceptions
7. To use the finally clause in a try-catch block
8. To declare exceptions in a method header (throws)
9. To throw exceptions in a method
10. To define custom exception classes
2
Exception-Handling
What is an exception?
• An exception is an abnormal condition that arises in a code sequence at
run time.
• An exception is a run-time error.
• Exception handling avoids these problems and, in the process, brings run-
time error management into the object oriented world.
• Exception is an object that describes an exceptional 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. This exception is then caught and processed.
Object Oriented Programming 3
Throwable
• Throwable is at the top of the Exception class hierarchy.
• All exception types are subclasses of the built-in class Throwable.
• Throwable contains two subclasses
1. Exception
2. Error
Object Oriented Programming 4
Error
• One branch of Throwable is topped by Error class, which defines
exceptions that are not expected to be caught under normal
circumstances by a program or application.
• Exceptions of type Error are used by the Java run-time system to indicate
errors having to do with the run-time environment, itself.
• Example:
– Stack overflow
– Out of Memory
• These are typically created in response to catastrophic failures that cannot
usually be handled by a program.
Object Oriented Programming 5
Exception
• The second branch of Throwable is headed by Exception. This class is used
for exceptional conditions that user programs should catch.
• Exception can further be classified into following 2 broad categories.
– Unchecked or RuntimeException
• Exceptions of this type are automatically defined for the programs
that is being written like division by zero and invalid array indexing.
• These are called unchecked exceptions because the compiler does
not check to see if a method handles or throws these exceptions.
– Checked Exception
• Checked Exception must be included in a method’s throws list if
that method can generate one of these exceptions and does not
handle it itself.
Object Oriented Programming 6
Exception Types
Object Oriented Programming 7
Uncaught Exceptions
class Exc0 {
public static void main(String args[]) {
int d = 0;
int a = 42 / d;
}
}
This small program includes an expression that intentionally causes a divide-
by-zero error
Object Oriented Programming 8
How an exception is propagated?
• When the Java run-time system detects the attempt to divide by zero, it
constructs a new exception object and then throws this exception. Once
an exception has been thrown, it must be caught by an exception handler
and dealt with immediately.
• In this example, exception handlers is not defined, so the exception is
caught by the default handler provided by the Java run-time system.
• The default handler displays a string describing the exception, prints a
stack trace from the point at which the exception occurred, and
terminates the program.
Object Oriented Programming 9
Uncaught Exceptions
Object Oriented Programming 10
Exception handling in Java
• Although the default exception handler is useful for debugging, but
exceptions can also be handled by program for two reason;
– it allows you to fix the error.
– it prevents the program from automatically terminating.
• Java exception handling is managed via five keywords:
Exception Handling
try catch finally throw throws
Object Oriented Programming 11
try
• The try statement allows you to define a block of code to be tested for
errors while it is being executed.
• Program statements that you want to monitor for exceptions are
contained within a try block. If an exception occurs within the try block, it
is thrown.
• The statements that are protected by try must be surrounded by curly
braces. (That is, they must be within a block.) You cannot use try on a
single statement.
Object Oriented Programming 12
catch
• The catch statement allows you to define a block of code to be executed,
if an error occurs in the try block.
• Immediately following the try block, include a catch clause that specifies
the exception type that you wish to catch.
• ExceptionType is the type of exception that has occurred.
• The scope of the catch clause is restricted to those statements specified
by the immediately preceding try statement. A catch statement cannot
catch an exception thrown by another try statement.
• The goal of most well-constructed catch clauses should be to resolve the
exceptional condition and then continue on as if the error had never
happened.
Object Oriented Programming 13
Using try-catch
Output
Object Oriented Programming 14
Using try-catch
• In the example, 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.
• Put differently, catch is not “called,” so execution never “returns” to
the try block from a catch. Thus, the line “After Exception ” is not
displayed.
• Once the catch statement has executed, program control continues
with the next line in the program following the entire try/catch
mechanism.
Object Oriented Programming 15
Displaying Exception Description
• Throwable overrides the toString( ) method (defined by Object) so that it
returns a string containing a description of the exception. You can display
this description in a println( ) statement by simply passing the exception as
an argument.
Output
Object Oriented Programming 16
Multiple catch Clauses
• In some cases, more than one exception could be raised by a single piece
of code.
• 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.
Object Oriented Programming 17
Multiple catch Clauses
Object Oriented Programming 18
Multiple catch Clauses
Output:
Object Oriented Programming 19
Multiple catch Clauses
• When you use multiple catch statements, it is important to remember that
exception subclasses must come before any of their superclasses.
Object Oriented Programming 20
Nested try Statements
• The try statement can be nested.
• That is, a try statement can be inside the block of another try. If an inner
try statement does not have a catch handler for a particular exception, 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.
• Nesting of try statements can also occur when method calls are involved.
For example, you can enclose a call to a method within a try block. Inside
that method is another try statement. In this case, the try within the
method is still nested.
Object Oriented Programming 21
Nested try Statements
try {
try {
int a = 10;
a = 10 / 0;
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("catch 1 ");
}
}
catch (ArithmeticException e) {
System.out.println(“ catch 2");
}
Object Oriented Programming 22
Practice!
• Write a simple java program that adds two integers input by user. The
program should terminate if any operand is nonnumeric. Before program
exit, a message should be displayed that “Input is not valid!”.
Hint: You can use
– NumberFormatException
– InputMismatchException
Object Oriented Programming 23
finally
• Any code that absolutely must be executed after a try block completes is
put in a finally block.
• 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.
Object Oriented Programming 24
A try and its catch along with finally statement form a unit. The
finally clause is optional. However, each try statement requires at
least one catch or a finally clause.
Object Oriented Programming 25
finally
• When exceptions are thrown, execution in a method takes a rather
abrupt, nonlinear path that alters the normal flow through the method.
• Depending upon how the method is coded, it is even possible for an
exception to cause the method to return prematurely. This could be a
problem in some methods.
• 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
Object Oriented Programming 26
finally
• Throw an exception out of the method.
static void procA() {
try {
System.out.println("inside procA");
Int I =10 / 0;
}
finally {
System.out.println("procA's finally"); }
}
Object Oriented Programming 27
finally
• Return from within a try block
Object Oriented Programming 28
finally
• Execute a try block normally.
Object Oriented Programming 29
finally
• Calling all three methods in main method;
Output:
Object Oriented Programming 30
throw
• System-generated exceptions are automatically thrown by the Java run-
time system. However it is possible for a program to throw an exception
explicitly, using the throw statement.
• The general form of throw is shown here:
• ThrowableInstance must be an object of type Throwable or a subclass of
Throwable.
• There are two ways you can obtain a Throwable object:
1. using a parameter in a catch clause, or
2. creating one with the new operator.
Object Oriented Programming 31
throw
• 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.
• Many of Java’s built in run-time exceptions have at least two constructors:
1. one with no parameter and
2. one that takes a string parameter.
Object Oriented Programming 32
Output
Object Oriented Programming 33
throws
• Any exception that is thrown out of a method must be specified as such by
a throws clause.
• throws clause lists the types of exceptions that a method might throw.
• If a method is capable of causing an exception that it does not handle, it
must specify this behavior so that callers of the method can guard
themselves against that exception. This can be achieved by including a
throws clause in the method’s declaration.
Object Oriented Programming 34
throws
• All exceptions other than that of type Error or RuntimeException or any of
their subclasses, that a method can throw must be declared in the throws
clause. If they are not, a compile-time error will result.
Object Oriented Programming 35
throws
public void readFile()
{
FileReader t = new FileReader("data/data.csv"); Error
}
public void readFile() throws FileNotFoundException
{
FileReader t = new FileReader("data/data.csv");
}
Object Oriented Programming 36
throws
public static void main(String[] args) {
readFile(); Error
}
public static void main(String[] args) {
try {
readFile();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
Object Oriented Programming 37
Java’s Built-in Exceptions
• The most general exceptions are subclasses of the standard type
RuntimeException.
• In the language of Java, these are called unchecked exceptions because
the compiler does not check to see if a method handles or throws these
exceptions.
• The unchecked exceptions defined in java.lang are listed in Table.
Object Oriented Programming 38
Java’s Built-in Exceptions
Object Oriented Programming 39
Java’s Built-in Exceptions
• There are exceptions that must be included in a method’s throws list if
that method can generate one of these exceptions and does not handle it
itself. These are called checked exceptions. Table lists such exceptions
defined by java.lang.
Object Oriented Programming 40
Custom Exception
• You can define a custom exception class by extending the
java.lang.Exception class.
• Java provides quite a few exception classes. Use them whenever possible
instead of defining your own exception classes. However, if you run into a
problem that cannot be adequately described by the predefined exception
classes, you can create your own exception class, derived from Exception
or from a subclass of Exception, such as IOException
Object Oriented Programming 41
Custom Exception
Object Oriented Programming 42
Practice!
Write a class InvalidCNICException that extends Exception class.
The class should have following details implemented
– A message property.
– override following method that returns message
String toString()
– Two constructors
1. With no parameter
2. With String parameter
Take user input for CNIC. The CNIC is considered valid if
1. The length of CNIC is 15(including -)
2. if the hyphen(-) is present at position 6 and 14.
Generate (throw) InvalidCNICException when an invalid CNIC has been entered by the
user. Handle this exception by giving user a responsive message saying "The CNIC you
entered is not valid"
Object Oriented Programming 43