EXCEPTION IN JAVA
EXCEPTION IN JAVA
EXCEPTION IN JAVA
What is an Exception?
An exception is an “unwanted or unexpected event”, which occurs during the execution of the
program i.e, at run-time, that disrupts the normal flow of the program’s instructions. When an
exception occurs, the execution of the program gets terminated.
An exception is an unexpected event that occurs during program execution. It affects the flow of
the program instructions which can cause the program to terminate abnormally.
An exception can occur for many reasons. Some of them are:
Invalid user input
Device failure
Loss of network connection
Physical limitations (out of disk memory)
Code errors
Opening an unavailable file
Java Exception hierarchy
Here is a simplified diagram of the exception hierarchy in Java.
Errors
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.
Exceptions
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 state of the program when the exception occurred.
try {
catch (ArithmeticException e) {
System.out.println("ArithmeticException => " + e.getMessage());
}
}
}
Output
ArithmeticException => / by zero
Example 2
class Division {
public static void main(String[] args)
{
int a = 10, b = 5, c = 5, result;
try {
result = a / (b - c);
System.out.println("result" + result);
}
catch (ArithmeticException e) {
System.out.println("Exception caught:Division by zero");
}
}
}
Output
Exception caught:Division by zero
class Main {
public static void main(String[] args) {
try {
// code that generates exception
int divideByZero = 5 / 0;
}
catch (ArithmeticException e) {
System.out.println("ArithmeticException => " + e.getMessage());
}
finally {
System.out.println("This is the finally block");
}
}
}
Output
ArithmeticException => / by zero
This is the finally block
Java throw and throws keyword
The Java throw keyword is used to explicitly throw a single exception.
When we throw an exception, the flow of the program moves from the try block to the catch
block.
Example: Exception handling using Java throw
class Main {
public static void divideByZero() {
// throw an exception
throw new ArithmeticException("Trying to divide by 0");
}
public static void main(String[] args) {
divideByZero();
}
}
Output
Exception in thread "main" java.lang.ArithmeticException: Trying to divide by
0
at Main.divideByZero(Main.java:5)
at Main.main(Main.java:9)