Java - Exceptions
Why we use Exception Handling in Java?
Java provides a sophisticated exception handling mechanism that
enables you to detect exceptional conditions in your programs and fix
the exceptions as and when they occur. Using exception handling
features offers several advantages.
• Complete Program Execution
• Easy Identification of Program Code and Error-Handling Code
• Propagation of Errors
• Meaningful Error Reporting
• Identifying Error Types
Complete Program Execution
• One of the important purposes of exception handling in Java is to
continue program execution after an exception is caught and handled.
• The execution of a Java program does not terminate when an
exception occurs. Once the exception is resolved, program execution
continues till completion.
• By using well-structured try, catch, and finally blocks, you can create
programs that fix exceptions and continue execution as if there were
no errors. If there is a possibility of more than one exception, you can
use multiple catch blocks to handle the different exceptions.
Easy Identification of Program Code and Error-
Handling Code:
• The use of try/catch blocks segregates error-handling code and
program code making it easier to identify the logical flow of a
program. The logic in the program code does not include details of
the actions to be performed when an exception occurs. Such details
are present in the catch blocks.
• Unlike many traditional programming languages that include
confusing error reporting and error handling code in between the
program code, Java allows you to create well-organized code.
Separating error handling and program logic in this way makes it
easier to understand and maintain programs in the long run.
Propagation of Errors:
• Java’s exception handling mechanism works in such a way that error
reports are propagated up the call stack. This is because whenever an
exception occurs, Java’s runtime environment checks the call stack
backwards to identify methods that can catch the exception.
• When a program includes several calls between methods,
propagation of exceptions up the call stack ensures that exceptions
are caught by the right methods.
Meaningful Error Reporting:
• The exceptions thrown in a Java program are objects of a class. Since
the Throwable class overrides the toString() method, you can obtain a
description of an exception in the form of a string and display the
description using a println() statement.
Identifying Error Types:
Java provides several super classes and sub classes that group
exceptions based on their type. While the super classes like
IOException provide functionality to handle exceptions of a general
type, sub classes like FileNotFoundException provide functionality to
handle specific exception types.
• The core advantage of exception handling is to maintain the normal
flow of the application. An exception normally disrupts the normal
flow of the application; that is why we need to handle exceptions.
Let's consider a scenario:
Suppose there are 10 statements in a Java program and an exception
occurs at statement 5; the rest of the code will not be executed, i.e.,
statements 6 to 10 will not be executed. However, when we perform
exception handling, the rest of the statements will be executed. That is
why we use exception handling in Java.
Java - Exceptions
An exception (or exceptional event) is a problem that arises during the
execution of a program. 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.
An exception can occur for many different reasons. Following are some
scenarios where an exception occurs.
• A user has entered an invalid data.
• A file that needs to be opened cannot be found.
• A network connection has been lost in the middle of communications
or the JVM has run out of memory.
The Exception Handling in Java is one of the powerful mechanism to
handle the runtime errors so that the normal flow of the application
can be maintained.
Some of these exceptions are caused by user error, others by
programmer error, and others by physical resources that have failed in
some manner.
Based on these, we have three categories of Exceptions. You need to
understand them to know how exception handling works in Java.
1. Checked exceptions
2. Unchecked exceptions
3. Errors
Checked exceptions
Checked exceptions − A checked exception is an exception that is
checked (notified) by the compiler at compilation-time, these are also
called as compile time exceptions. These exceptions cannot simply be
ignored, the programmer should take care of (handle) these
exceptions.
• For example, if you use FileReader class in your program to read data
from a file, if the file specified in its constructor doesn't exist, then a
FileNotFoundException occurs, and the compiler prompts the
programmer to handle the exception.
Unchecked exceptions
Unchecked exceptions − An unchecked exception is an exception that
occurs at the time 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.
Errors
Errors − These are not exceptions at all, but problems that arise beyond
the control of the user or the programmer. Errors are typically ignored
in your code because you can rarely do anything about an error. For
example, if a stack overflow occurs, an error will arise. They are also
ignored at the time of compilation.
Exception Hierarchy
• All exception classes are subtypes of the [Link] class.
The exception class is a subclass of the Throwable class. Other than
the exception class there is another subclass called Error which is
derived from the Throwable class.
Java Exception Keywords
try The "try" keyword is used to specify a block where we should place an exception code. It
means we can't use try block alone. The try block must be followed by either catch or finally.
catch The "catch" block is used to handle the exception. It must be preceded by try block which
means we can't use catch block alone. It can be followed by finally block later.
finally The "finally" block is used to execute the necessary code of the program. It is executed
whether an exception is handled or not.
throw The "throw" keyword is used to throw an exception.
throws The "throws" keyword is used to declare exceptions. It specifies that there may occur an
exception in the method. It doesn't throw an exception. It is always used with method
signature.
Java Exception Handling Example
Java try-catch block
• Java try block is used to enclose the code that might throw an
exception. It must be used within the method.
• If an exception occurs at the particular statement in the try block, the
rest of the block code will not execute. So, it is recommended not to
keep the code in try block that will not throw an exception.
• Java try block must be followed by either catch or finally block.
Java catch block
• Java catch block is used to handle the Exception by declaring the type
of exception within the parameter. The declared exception must be
the parent class exception ( i.e., Exception) or the generated
exception type. However, the good approach is to declare the
generated type of exception.
• The catch block must be used after the try block only. You can use
multiple catch block with a single try block.
Internal Working of Java try-catch block
Problem without exception
handling
Custom message on exception
Checked exception
Unchecked exception
Java Catch Multiple Exceptions
A try block can be followed by one or more catch blocks. Each catch
block must contain a different exception handler. So, if you have to
perform different tasks at the occurrence of different exceptions, use
java
Example
Java Nested try block
• 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.
• For example, the inner try block can be used to handle
ArrayIndexOutOfBoundsException while the outer try block can
handle the ArithemeticException (division by zero).
• Sometimes a situation may arise where a part of a block may cause
one error and the entire block itself may cause another error. In such
cases, exception handlers have to be nested.
Example
Java finally block
• Java finally block is a block used to execute important code such as
closing the connection, etc.
• Java finally block is always executed whether an exception is handled
or not. Therefore, it contains all the necessary statements that need
to be printed regardless of the exception occurs or not.
• The finally block follows the try-catch block.
Flowchart of finally block
When an exception
does not occur
When an exception occur but not handled by
the catch block
When an exception occurs and is handled by
the catch block
Java throw keyword
• The Java throw keyword is used to throw an exception explicitly.
• We specify the exception object which is to be thrown. The Exception has
some message with it that provides the error description. These exceptions
may be related to user inputs, server, etc.
• We can throw either checked or unchecked exceptions in Java by throw
keyword. It is mainly used to throw a custom exception. We will discuss
custom exceptions later in this section.
• We can also define our own set of conditions and throw an exception
explicitly using throw keyword. For example, we can throw
ArithmeticException if we divide a number by another number. Here, we
just need to set the condition and throw exception using throw keyword.
Syntax
The syntax of the Java throw keyword is given below.
Throwing Unchecked Exception
Throwing Checked Exception
Throwing User-defined Exception
Java throws keyword
• The Java throws keyword is used to declare an exception. It gives an
information to the programmer that there may occur an exception.
So, it is better for the programmer to provide the exception handling
code so that the normal flow of the program can be maintained.
• Exception Handling is mainly used to handle the checked exceptions.
If there occurs any unchecked exception such as
NullPointerException, it is programmers' fault that he is not checking
the code before it being used.
• Syntax of Java throws
Example
Example