What Is An Exception in Java
What Is An Exception in Java
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.
Output
Welcome to ScholarHat
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. 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
use multiple catch statements for different kinds of exceptions that can occur from a single
block of code in the try block.
Syntax
try {
// code to check exceptions
}
catch (exception1) {
// code to handle the exception
}
catch (exception2) {
// code to handle the exception
}
.
.
.
catch (exception n) {
// code to handle the exception
}
Example
public class MultipleCatchBlock {
try {
int x[] = new int[5];
x[5] = 40 / 0;
} catch (ArithmeticException e) {
System.out.println("Arithmetic Exception occurs");
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("ArrayIndexOutOfBounds Exception occurs");
} catch (Exception e) {
System.out.println("Parent Exception occurs");
}
System.out.println("The program ends here");
}
}
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
The program ends here
Nested try-catch
System.out.println(arr[10]);
} catch (ArithmeticException e) {
System.out.print("Arithmetic Exception");
System.out.println(" handled in try-block3");
}
} catch (ArithmeticException e) {
System.out.print("Arithmetic Exception");
System.out.println(" handled in try-block2");
}
} catch (ArithmeticException e3) {
System.out.print("Arithmetic Exception");
System.out.println(" handled in main try-block");
} catch (ArrayIndexOutOfBoundsException e4) {
System.out.print("ArrayIndexOutOfBoundsException");
System.out.println(" handled in main try-block");
} catch (Exception e5) {
System.out.print("Exception");
System.out.println(" handled in main try-block");
}
}
}
In the above code, the ArrayIndexOutOfBoundsException occurred in the grandchild try-
block3. Since try-block3 is not handling this exception, the control then gets transferred to
the parent try-block2. Since try-block2 also does not handle that exception, the control gets
transferred to the main try-block, where it finds the appropriate catch block for an exception.
Output
ArrayIndexOutOfBoundsException handled in main try-block
3. finally
The finally block in Java always executes even if there are no exceptions. This is an optional block. It
is used to execute important statements such as closing statements, releasing resources, and
releasing memory. There could be one final block for every try block. This finally block executes after
the try...catch block.
Syntax
try
{
//code
}
catch (ExceptionType1 e1)
{
// catch block
}
finally
{
// finally block always executes
}
Output
ArithmeticException => / by zero
This is the finally block
final Vs. finally Vs. finalize in Java
final finally finalize
final is a keyword and access finally is the block in Java finalize is the method in Java
modifier, which is used to apply Exception Handling to execute that is used to perform clean-
restrictions on a class, method, or the important code whether the up processing just before an
variable. exception occurs or not. object is garbage collected.
Finally, the block is always
The final keyword is used with the finalize() method is used with
related to the try-catch block in
classes, methods, and variables. the objects.
exception handling.
It is used with variables, methods, It is with the try-catch block in
Used with objects
and classes. exception handling.
Once declared, the final variable
becomes constant and can't be finalize method performs the
finally block cleans up all the
modified. A sub-class can neither cleaning concerning the object
resources used in the try block
override a final method nor can the before its destruction
final class be inherited.
finally block executes as soon as
finalize method is executed
final method is executed only when the execution of the try-catch
just before the object is
we call it block is completed without
destroyed
depending on the exception
4. throw
The throw keyword is used to explicitly throw a checked or an unchecked exception.
The exception that is thrown needs to be of type Throwable or a subclass of Throwable.
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
throw new exception_class("error message");
Output
Caught an exception: Number cannot be negative
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;
2. NullPointerException
This occurs when a user tries to access a variable that stores null values. For example, if a variable
stores a null value and the user tries to perform any operation on that variable, a
NullPointerException will be thrown.
String s=null;
System.out.println(s.length());//NullPointerException
3. NumberFormatException
If the formatting of any variable or number is mismatched, it may result in a
NumberFormatException.
String s="ScholarHat";
int i=Integer.parseInt(s);//NumberFormatException
4. ArrayIndexOutOfBoundsException
When an array exceeds its size, the ArrayIndexOutOfBoundsException occurs.
int a[]=new int[6];
a[10]=80; //ArrayIndexOutOfBoundsException
5. StringIndexOutOfBoundsException
It is the same as ArrayIndexOutOfBoundsException but it is for strings instead of arrays. Here if the
length of a string is less than what we are trying to access there occurs the
StringIndexOutOfBoundsException.
String s = "I am learning Java on ScholarHat.";
System.out.println("String length is:" + s.length());
System.out.println("Length of substring is:" + s1.substring(40));
//StringIndexOutOfBoundsException