Exception handling in Java
What is Exception ?
An 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.
Error VS Exception:
Errors | Exceptions |
---|---|
Errors are usually raised by the environment in which the application is running. For example, an error will occur due to a lack of system resources. | Exceptions are caused by the code of the application itself. |
It is not possible to recover from an error. | The use of try-catch blocks can handle exceptions and recover the application from them. |
Errors occur at run-time and are not known by the compiler; hence, they are classified as “unchecked.” | Exceptions can be “checked” or “unchecked,” meaning they may or may not be caught by the compiler. |
“OutOfMemory” and “StackOverflow” are examples of errors. | “IndexOutOfBounds” is an example of an unchecked exception, while “ClassNotFound” is an example of a checked exception. |
Types of exceptions in java :-
Checked Exceptions :-
- Those exceptions that are checked at compile-time comprises checked exceptions.
- The program will not compile if they are not handled.
- Example: IOException, ClassNotFoundException, etc.
Un-checked Exceptions :-
- Those exceptions that are checked at runtime comprises unchecked exceptions.
- They give runtime errors if not handled explicitly.
- Example: ArithmeticException, NullPointerException etc.
Exception Hierarchy :-
All exception and errors types are sub classes of class Throwable, which is base class of hierarchy.One branch is headed
by Exception. This class is used for exceptional conditions that user programs should catch. NullPointerException is an
example of such an exception.Another branch,Error are used by the Java run-time system(JVM) to indicate errors
having to do with the run-time environment itself(JRE). StackOverflowError is an example of such an error.
Java Exception Keywords :-
Exception Handling in java is managed via five keywords: try, catch, throw, throws, and finally. Here are 5 keywords that are used in handling exceptions in Java
Keyword | Description |
try | This keyword is used to specify a block and this block must be followed by either catch or finally. That is, we can’t use try block alone. |
catch | This keyword must be preceded by a try block to handle the exception and can be followed by a final block later. |
finally | This keyword is used to execute the program, whether an exception is handled or not. |
throw | This keyword is used to throw an exception. |
throws | This keyword is used to declare exceptions. |
Java try-catch :-
The try-catch block in Java is used to handle exceptions and prevents the abnormal termination of the program. Here is the syntax for try-catch block: in java
try{
// code
}
catch(exception) {
// code
}
The try block includes the code that might generate an exception.
The catch block includes the code that is executed when there occurs an exception inside the try block
Java try-catch Example :-
class Main {
public static void main(String[] args) {
try {
int divideByZero = 5 / 0;
System.out.println("Rest of code in try block");
}
catch (ArithmeticException e) {
System.out.println(e);
}
}
}
Output :-
java.lang.ArithmeticException: / by zero
Java Finally Block :-
We can also use the try block along with a finally block.
In this case, the finally block is always executed whether there is an exception inside the try block or not.
Example For java finally block :-
class Main {
public static void main(String[] args) {
try {
int divideByZero = 5 / 0;
}
finally {
System.out.println("Finally block is always executed");
}
}
}
Output:
Finally block is always executed
Exception in thread "main" java.lang.ArithmeticException: / by zero
at Main.main(Main.java:4)
Java multiple catch block :-
For each try block , there can be zero or more catch blocks. Multiple catch blocks allows to handle each exception differently
The argument type of each catch block indicates the type of exception that can be handled by it.
Syntax For java multiple catch block:
try{
// code
}
catch(Exception e1){}
catch(Exception e2){}
Catching Multiple Exceptions :-
From Java SE 7 and later, we can now catch more than one type of exception with one catch block.
This reduces code duplication and increases code simplicity and efficiency.
Each exception type that can be handled by the catch block is separated using a vertical bar | .
Syntax for catching multiple exceptions :-
try {
// code
}
catch (ExceptionType1 | Exceptiontype2 ex){
// 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.
Syntax:
throw new exception_class("error message");
Java throw keyword example :-
public class Main {
static void checkAge(int age) {
if (age < 18) {
throw new ArithmeticException("Access denied - You must be at least 18 years old.");
}
else {
System.out.println("Access granted - You are old enough!");
}
}
public static void main(String[] args) {
checkAge(15); // Set age to 15 (which is below 18...)
}
}
Output :-
Exception in thread "main" java.lang.ArithmeticException: Access denied - You must be at least 18 years old.
at Main.checkAge(Main.java:4)
at Main.main(Main.java:11)
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.
Syntax:
return_type method_name() throws exception_class_name{
// method code
}
Java throws keyword example :-
public class Main {
static void checkAge(int age) throws ArithmeticException {
if (age < 18) {
throw new ArithmeticException("Access denied - You must be at least 18 years old.");
}
else {
System.out.println("Access granted - You are old enough!");
}
}
public static void main(String[] args) {
checkAge(15); // Set age to 15 (which is below 18...)
}
}
Output :-
Exception in thread "main" java.lang.ArithmeticException: Access denied - You must be at least 18 years old.
at Main.checkAge(Main.java:4)
at Main.main(Main.java:11)
Great and informative!