Exception Handling in Jav1
Exception Handling in Jav1
Exception Handling in Java is an effective method for dealing with unwanted and unexpected events during program execution
while maintaining the application's usual flow. When learning Java, one must be ready to deal with errors, unexpected inputs, or
other exceptions.
Exceptions are unwanted events that disrupt the program's execution. Many a time, your program looks error-free after writing
the code. But, at the time of execution, some unexpected errors or events or objects come to the surface, and the program prints
an error message and stops executing. Such unexpected happenings are called exceptions in Java.
System Failure
Network Problem
Security Compromises
Errors in Code
Physical Limitations
Exception Handling is a way of handling errors that occur during runtime and compile time. It maintains your program flow despite
runtime errors in the code and, thus, prevents unanticipated crashes. It facilitates troubleshooting by providing error details,
cutting down on development time, and improving user happiness.
Exception and Error are subclasses of Throwable, the hierarchy's base class. Exception, for example, is used for exceptional
conditions that user programs should catch. Error, on the other hand, is used by the Java run-time system (JVM) to indicate errors
1. Errors: An error is a severe condition that can occur only at run time and is irrecoverable. It prevents a program from
executing and cannot be handled by the programmer. An error belongs to the java.lang.error class.
2. Exceptions: A programmer can catch and handle exceptions in his program code. When an exception occurs within a
method, an object called the exception object is created. This object contains information about the exception, such as its
name and description and the state of the program when the exception occurred.
1. Built-in Exceptions
These exceptions are present in Java libraries.
1. Checked Exception
Checked exceptions are classes that inherit directly from the Throwable class, with the exception of RuntimeException and Error.
Examples include IOException, SQLException, and so on. Checked exceptions are checked at compilation time. They must be either
caught by the code or declared in the method signature using the throws keyword.
2. Unchecked Exception
Classes that inherit the RuntimeException class are known as unchecked exceptions. Examples include ArithmeticException,
NullPointerException, and ArrayIndexOutOfBoundsException. Unchecked exceptions are not checked at compile-time but rather at
runtime by JVM. They do not need to be explicitly caught or declared.
2. User-Defined Exceptions
User-defined exceptions are also known as custom exceptions derived from the Exception class from java.lang package. The user
creates these exceptions according to different situations. Such exceptions are handled using five keywords: try, catch, throw,
throws, and finally.
We'll learn how to use these keywords in the Exception Handling Keywords in Java section below.
Errors Exceptions
Errors are of Unchecked type Exceptions can be both checked and unchecked.
Errors mainly occur during run-time. Only the unchecked exceptions are encountered in run-time.
Java consists of five keywords to handle various kinds of custom exceptions. They are:
Keyword Description
catch specifies the code block to be executed if an exception occurs in the try block.
finally the finally block will always be executed whether an exception occurs or not
1. try
A try block consists of all the doubtful statements that can throw exceptions.
A try block cannot be executed on itself; it requires at least one catch block or finally block.
When an exception occurs in a try block, the appropriate exception object is redirected to the catch block. This catch block
handles the exception according to its statements and continues the execution.
Syntax
try
//Doubtful Statements.
2. catch
The catch block handles the exception raised in the try block.
The catch block catches the thrown exception as its parameter and executes the statements inside it.
The declared exception must be the parent class exception, the generated exception type in the exception class hierarchy,
or a user-defined exception.
Syntax
try
// code
catch(Exception e)
Examples IIlustrating Implementation of try-catch blocks for Java Exception Handling in Java Online Compiler
2.
3. class Main
4. {
7. try
8. {
12. }
15. }
16. }
In the above code, we have put the "int divideByZero=5/0" in the try block because this statement must not be executed if the
denominator is 0. If the denominator is 0, the statements after this statement in the try block are skipped. The catch block catches
the thrown exception as its parameter and executes the statements inside it.
Output
We can use multiple catch statements for different kinds of exceptions that can occur from a single block of code in the try block.
Syntax
try {
catch (exception1) {
catch (exception2) {
catch (exception n) {
Example
try {
x[5] = 40 / 0;
} catch (ArithmeticException e) {
} catch (ArrayIndexOutOfBoundsException e) {
} catch (Exception e) {
Here, our program matches the type of exception that occurred in the try block with the catch statements. If the exception that
occurred matches any of the usual catch statements, that particular catch block gets executed.
Output
Arithmetic Exception occurs
4. throw
We can also define our own set of conditions for which we can throw an exception explicitly using the throw keyword.
The program's execution flow stops immediately after the throw statement is executed, and the nearest try block is
checked to see if it has a catch statement that matches the type of exception.
Syntax
class ThrowExample {
if (number < 0) {
} else {
try {
checkNumber(-5);
} catch (IllegalArgumentException e) {
5. throws
The throws keyword is used in the method signature to indicate that a method in Java can throw particular exceptions. This
notifies the method that it must manage or propagate these exceptions to the caller.
import java.io.IOException;
try {
methodWithException();
} catch (IOException e) {
// Simulate an IOException