2. Introduction
• A program can fail for just about any reason. Here are just a few
possibilities:
• The code tries to connect to a website, but the Internet connection is down.
• You made a coding mistake and tried to access an invalid index in an array.
• One method calls another with a value that the method doesn’t support.
• The code tries to connect to a website, but the power goes off.
• You are trying to create an object of some class, Class Not Found
• You try to read from a File, File Not Found
• The code tries to connect to database, database is not available, connection
failed….
3. Introduction
• Some of these are coding mistakes. Others are completely beyond
your control.
• Your program can’t help it if the Internet connection goes down.
What it can do is deal with the situation.
• Happy path, Unhappy path
• When Java was a kid…
• These are the two approaches Java uses when dealing with
exceptions. A method can handle the exception case itself or make it
the caller’s responsibility.
6. When we can use Exceptions?
• Exceptions can and do occur all the time, even in solid program code.
• When you write more advanced programs, you’ll need to deal with
failures in accessing files, networks, and outside services.
• Exceptions are used when “something goes wrong.”
• Exception while Search not found – return a special value
• An exception should be reserved for exceptional conditions like
names being null.
• An exception forces the program to deal with them or end.
• With the exception if left unhandled, whereas a return code could be
accidentally ignored and cause problems later in the program.
• An exception is like shouting, “Deal with me!”
7. Without Exception handling
• Consider statements in flow
statement 1;
statement 2;
statement 3;
statement 4;
statement 5; //exception occurs - statements 6 to 9 will not get executed
statement 6;
statement 7;
Statement 8;
Statement 9;
11. After Handling Exceptions
• The exception handling in java is one of the powerful mechanism to handle the runtime
errors so that normal flow of the application can be maintained.- Smooth Termination
• Exception is an event that alters program flow.
• Consider statements in flow
statement 1;
statement 2;
statement 3;
statement 4;
statement 5; // If we perform exception handling - statements 6 to 9 will get executed
statement 6;
statement 7;
Statement 8;
Statement 9;
14. Understanding Exception Types: Error
• Error means something went so horribly wrong that your program
should not attempt to recover from it.
• These are exceptional conditions that are external to the application,
and that the application usually cannot anticipate or recover from.
• Ex. suppose that an application successfully opens a file for input, but
is unable to read the file because of a hardware or system
malfunction.
• The unsuccessful read will throw java.io.IOError.
• Errors are not subject to the Catch or Specify Requirement. Errors are
those exceptions indicated by Error and its subclasses.
15. Exception Types: Runtime Exception
• These are exceptional conditions that are internal to the application, and
that the application usually cannot anticipate or recover from.
• These usually indicate programming bugs, such as logic errors or improper
use of an API.
• Ex1: consider the application described previously that passes a file name
to the constructor for FileReader. If a logic error causes a null to be passed
to the constructor, the constructor will throw NullPointerException.
• The application can catch this exception, but it probably makes more sense
to eliminate the bug that caused the exception to occur.
• Runtime exceptions tend to be unexpected but not necessarily fatal.
• Ex2: accessing an invalid array index is unexpected.
• Runtime exception is defined as the RuntimeException class and its
subclasses.
17. Understanding Exception Types
• A checked exception includes Exception and all subclasses that do not extend
RuntimeException.
• Checked exceptions tend to be more anticipated—for example, trying to read a
file that doesn’t exist.
• Checked exceptions are checked at compile-time.
• Java has a rule called the handle or declare rule.
• For checked exceptions, Java requires the code to either handle them or declare
them in the method signature.
• For example, this method declares that it might throw an exception:
void fall() throws Exception {
throw new Exception();
}
18. Checked Exception
• These are exceptional conditions that a well-written application should
anticipate and recover from.
• For example, suppose an application prompts a user for an input file name,
then opens the file by passing the name to the constructor for
java.io.FileReader. Normally, the user provides the name of an existing,
readable file, so the construction of the FileReader object succeeds, and
the execution of the application proceeds normally. But sometimes the
user supplies the name of a nonexistent file, and the constructor throws
java.io.FileNotFoundException. A well-written program will catch this
exception and notify the user of the mistake, possibly prompting for a
corrected file name.
• Checked exceptions are subject to the Catch or Specify Requirement. All
exceptions are checked exceptions, except for those indicated by Error,
RuntimeException, and their subclasses.
21. The try block
The first step in constructing an exception handler is to enclose the
code that might throw an exception within a try block. In general, a try
block looks like the following:
try {
code
}
catch and finally blocks . . .
22. What happens when an Exception is thrown?
• When an error occurs within a method, the method creates an object
and hands it off to the runtime system.
• The object, called an exception object, contains information about the
1. Error, including its type and
2. The state of the program when the error occurred.
23. Creating an exception object and handing it to the
runtime system is called throwing an exception.
24. The call stack
After a method throws an
exception, the runtime
system attempts to find
something to handle it.
The set of possible
"somethings" to handle
the exception is the
ordered list of methods
that had been called to get
to the method where the
error occurred. The list of
methods is known as
the call stack.
Method where error occurred
Method without an exception
handler
Method with an exception
handler
main
Method call
Method call
Method call
25. Searching the call stack for the exception handler
Method where error occurred
Method without an exception
handler
Method with an exception
handler
main
Looking for
appropriate
handler
Looking for
appropriate
handler
Throws Exception
Frorward Exception
Catches some other
Exception
26. Searching the call stack for the exception
handler
• The runtime system searches the call stack for a method that contains a
block of code that can handle the exception. This block of code is called
an exception handler. The search begins with the method in which the
error occurred and proceeds through the call stack in the reverse order in
which the methods were called. When an appropriate handler is found, the
runtime system passes the exception to the handler. An exception handler
is considered appropriate if the type of the exception object thrown
matches the type that can be handled by the handler.
• The exception handler chosen is said to catch the exception. If the runtime
system exhaustively searches all the methods on the call stack without
finding an appropriate exception handler, as shown in the next figure, the
runtime system (and, consequently, the program) terminates.
27. How to handle exception?
• We must use one of these pairs to handle the exception...
1. try - catch - [ similar to if else]
2. try - catch- finally
3. Try – multiple catch - finally
4. try - finally
28. i=0,
Income/0
Creates object of Exception,
search for catch block
Prints Exception type and
information
Executes finally block
Skips
execution
till catch
found
Resumes with rest of
the code after finally
1
30. Whichever exception occurs,
that matching catch block is
executed
Finally block gets executed
Rest of the code gets executed
after finally
Rest of the code gets executed
out of outer try block
Outer finally block gets
executed
2
32. Exception occurred, but no matching
catch block found
Finally block gets executed
Skipped
Rest of the code gets executed
Exception caught here
In case No matching catch block found in
inner try, nearest matching block is – Outer
catch block
Executes finally block of
outer try
3
38. Use of finally block
• The finally block always executes when the try block exits.
• This ensures that the finally block is executed even if an unexpected
exception occurs.
• But finally is useful for more than just exception handling — it allows
the programmer to avoid having cleanup code accidentally bypassed
by a return, continue, or break. Putting cleanup code in a finally block
is always a good practice, even when no exceptions are anticipated.
• Note: If the JVM exits while the try or catch code is being executed,
then the finally block may not execute. Likewise, if the thread
executing the try or catch code is interrupted or killed, the finally
block may not execute even though the application as a whole
continues.
39. Use of finally block
• The runtime system always executes the statements within the finally block
regardless of what happens within the try block. So it's the perfect place to
perform cleanup.
• The following finally block for the method cleans up and then closes the
PrintWriter.
• The finally block is a key tool for preventing resource leaks. When closing a file or
otherwise recovering resources, place the code in a finally block to ensure that
resource is always recovered.
finally {
if (out != null) {
System.out.println("Closing PrintWriter");
out.close();
} else {
System.out.println("PrintWriter not open");
}
}
40. The try-with-resources Statement
• Consider using the try-with-resources statement in these situations, which
automatically releases system resources when no longer needed.
1. static String readFirstLineFromFile(String path) throws IOException {
2. try (BufferedReader br = new BufferedReader(new FileReader(path))) {
3. return br.readLine();
4. }
5. }
• This example reads the first line from a file. It uses an instance of
BufferedReader to read data from the file. BufferedReader is a resource
that must be closed after the program is finished with it.
41. The try-with-finally Statement
• Prior to Java SE 7, you can use a finally block to ensure that a resource is closed
regardless of whether the try statement completes normally or abruptly. The following
example uses a finally block instead of a try-with-resources statement:
1. static String readFirstLineFromFileWithFinallyBlock(String path) throws IOException {
2. BufferedReader br = new BufferedReader(new FileReader(path));
3. try {
4. return br.readLine();
5. } finally {
6. if (br != null) br.close();
7. }
8. }
42. Throwing an Exception
• The throw keyword tells Java you want some other part of the code to
deal with the exception.
1. throw new Exception();
2. throw new Exception("Ow! I fell.");
• Above examples create a new object of type Exception and throw it.
• The Java throw keyword is used to explicitly throw an exception.
• We can throw either checked or unchecked exception.
• It is s mainly used to throw custom exception.
43. Specifying the Exceptions Thrown by a Method
using “throws” keyword
• To specify or to declare that method can throw exceptions, add a throws
clause to the method declaration for the that method.
• The throws clause comprises the throws keyword followed by a comma-
separated list of all the exceptions thrown by that method. The clause goes
after the method name and argument list and before the brace that defines
the scope of the method; here's an example.
public void writeList() throws IOException, IndexOutOfBoundsException {..}
• Here, IndexOutOfBoundsException is an unchecked exception; including it
in the throws clause is not mandatory.
• You could just write the following.
public void writeList() throws IOException {..}
47. Catching More Than One Type of Exception
with One Exception Handler
• In Java 7, catch block has been improved to handle multiple
exceptions in a single catch block. If you are catching multiple
exceptions and they have similar code, then using this feature will
reduce code duplication.
• In the catch clause, specify the types of exceptions that block can
handle, and separate each exception type with a vertical bar (|):
49. Chained Exceptions
• Exception handlers can do more than just print error messages or halt the
program. They can do error recovery, prompt the user to make a decision,
or propagate the error up to a higher-level handler using chained
exceptions.
• Throwing an exception along with another exception forms a chained
exception.
• In the preceding section, the catch block rethrows the original exception.
Sometimes, you may need to throw a new exception (with additional
information) along with the original exception.
• This is called chained exceptions.
• See example in next slide.
50. method2() is called from method1()
throws Exception
Catch block of caller
method gets executed
Catch block of caller
method gets executed
52. Defining Custom Exception Classes
• 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.
55. Exception Handling with MethodOverriding in
Java
• There are many rules if we talk about methodoverriding with
exception handling.
• If the superclass method does not declare an exception
• If the superclass method does not declare an exception, subclass overridden
method cannot declare the checked exception but it can declare unchecked
exception.
• If the superclass method declares an exception
• If the superclass method declares an exception, subclass overridden method
can declare same, subclass exception or no exception but cannot declare
parent exception.
56. If the superclass method does not declare an exception, subclass overridden
method cannot declare the checked exception.
Compilation Error
57. If the superclass method does not declare an exception, subclass overridden method cannot
declare the checked exception but can declare unchecked exception.
Output:
child
58. If the superclass method declares an exception, subclass overridden method can declare same,
subclass exception or no exception but cannot declare parent exception.
Output:
Compilation error
Subclass overridden method can declares same
exception – this is valid
59. Example in case subclass overridden method declares subclass exception
60. Advantages of Exceptions
• https://docs.oracle.com/javase/tutorial/essential/exceptions/advanta
ges.html
61. References
• http://www.geeksforgeeks.org
• Introduction to Java Programming, Comprehensive Version (10th
Edition), Y. Daniel Liang
• https://docs.oracle.com/javase/tutorial/essential/exceptions/advanta
ges.html
• https://www.javatpoint.com
• https://www.journaldev.com
• OCA Oracle Certified Associate Java SE 8 Programmer Study Guide
Exam 1Z0 808