Exception Handling Unit 3
Exception Handling Unit 3
errors so that the regular flow of the application can be preserved. Java Exception
Handling is a mechanism to handle runtime errors such as
ClassNotFoundException, IOException, SQLException, RemoteException, etc.
What are Java Exceptions?
In Java, Exception is an unwanted or unexpected event, which occurs during
the execution of a program, i.e. at run time, that disrupts the normal flow of the
program’s instructions. Exceptions can be caught and handled by the program.
When an exception occurs within a method, it creates an object. This object is
called the exception object. It contains information about the exception, such as
the name and description of the exception and the state of the program when the
exception occurred.
Major reasons why an exception Occurs
• Invalid user input
• Device failure
• Loss of network connection
• Physical limitations (out-of-disk memory)
• Code errors
• Opening an unavailable file
Errors represent irrecoverable conditions such as Java virtual machine (JVM)
running out of memory, memory leaks, stack overflow errors, library
incompatibility, infinite recursion, etc. Errors are usually beyond the control of the
programmer, and we should not try to handle errors.
Difference between Error and Exception
Let us discuss the most important part which is the differences between Error
and Exception that is as follows:
Types of Exceptions
Java defines several types of exceptions that relate to its various class libraries.
Java also allows users to define their own exceptions.
Exceptions can be categorized in two ways:
1. Built-in Exceptions
• Checked Exception
• Unchecked Exception
2. User-Defined Exceptions
Let us discuss the above-defined listed exception that is as follows:
1. Built-in Exceptions
Built-in exceptions are the exceptions that are available in Java libraries. These
exceptions are suitable to explain certain error situations.
• Checked Exceptions: Checked exceptions are called compile-time
exceptions because these exceptions are checked at compile-time by the
compiler.
2. User-Defined Exceptions:
Sometimes, the built-in exceptions in Java are not able to describe a certain
situation. In such cases, users can also create exceptions, which are called ‘user-
defined Exceptions’.
The advantages of Exception Handling in Java are as follows:
1. Provision to Complete Program Execution
2. Easy Identification of Program Code and Error-Handling Code
3. Propagation of Errors
4. Meaningful Error Reporting
5. Identifying Error Types
Methods to print the Exception information:
1. printStackTrace()
This method prints exception information in the format of the Name of the
exception: description of the exception, stack trace.
Example:
• Java
import java.io.*;
class GFG {
int a=5;
int b=0;
try{
System.out.println(a/b);
catch(ArithmeticException e){
e.printStackTrace();
}
Output
java.lang.ArithmeticException: / by zero
at GFG.main(File.java:10)
2. toString()
The toString() method prints exception information in the format of the Name of
the exception: description of the exception.
Example:
• Java
import java.io.*;
class GFG1 {
int a=5;
int b=0;
try{
System.out.println(a/b);
}
catch(ArithmeticException e){
System.out.println(e.toString());
Output
java.lang.ArithmeticException: / by zero
3. getMessage()
The getMessage() method prints only the description of the exception.
Example:
• Java
import java.io.*;
class GFG1 {
int a=5;
int b=0;
try{
System.out.println(a/b);
}
catch(ArithmeticException e){
System.out.println(e.getMessage());
Output
/ by zero
}
catch(Exception e) {
System.out.println(myNumbers[10]); // error!
Try it Yourself »
If an error occurs, we can use try...catch to catch the error and execute some
code to handle it:
Example
public class Main {
try {
System.out.println(myNumbers[10]);
} catch (Exception e) {
Try it Yourself »
Finally
The finally statement lets you execute code, after try...catch, regardless of the
result:
Example
public class Main {
try {
System.out.println(myNumbers[10]);
} catch (Exception e) {
} finally {
}
}
Try it Yourself »
we had to catch only one exception type in each catch block. So, whenever
we needed to handle more than one specific exception but take some action
for all exceptions, we had to have more than one catch block containing the
same code.
Syntax:
try {
// code
}
catch (ExceptionType1 | Exceptiontype2 ex){
// catch block
}
Flow Chart of Java Multiple Catch Block
FINALLY:-
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.
Syntax:
1. ....
2. //main try block
3. try
4. {
5. statement 1;
6. statement 2;
7. //try catch block within another try block
8. try
9. {
10. statement 3;
11. statement 4;
12. //try catch block within nested try block
Java throw
The throw keyword in Java is used to explicitly throw an exception from a
method or any block of code. We can throw either checked or unchecked
exception. The throw keyword is mainly used to throw custom exceptions.
Syntax in Java throw
throw Instance
Example:
throw new ArithmeticException("/ by zero");
But this exception i.e., Instance must be of type Throwable or a subclass
of Throwable.
Java throws
throws is a keyword in Java that is used in the signature of a method to indicate
that this method might throw one of the listed type exceptions. The caller to
these methods has to handle the exception using a try-catch block.
Syntax of Java throws
type method_name(parameters) throws exception_list
INTERFACE:-