Day 11 : Exception Handling in Java
POOJAASHREE P V
Full Stack Developer | JavaScript | Bootstrap | React | Spring Boot | MySQL
Exception :
An exception is an event that disrupts the normal flow of the program. It is an object which is thrown at runtime.
Exception Handling :
Exception Handling is a mechanism to handle runtime errors such as ClassNotFoundException, IOException, SQLException, RemoteException, etc.
Hierarchy of Java Exception classes :
The java.lang.Throwable class is the root class of Java Exception hierarchy inherited by two subclasses: Exception and Error.
Types of Java Exceptions
There are mainly two types of exceptions: checked and unchecked. An error is considered as the unchecked exception. According to Oracle, there are three types of exceptions namely:
Checked Exception :
The classes that directly inherit the Throwable class except RuntimeException and Error are known as checked exceptions. For example, IOException, SQLException, etc. Checked exceptions are checked at compile-time.
Unchecked Exception :
The classes that inherit the RuntimeException are known as unchecked exceptions. For example, ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException, etc. Unchecked exceptions are not checked at compile-time, but they are checked at runtime.
Error :
Error is irrecoverable. Some example of errors are OutOfMemoryError, VirtualMachineError, AssertionError etc.
Java Exception Keywords :
try :
The "try" keyword is used to specify a block where we should place an exception code. It means we can't use try block alone. The try block must be followed by either catch or finally.
catch :
The "catch" block is used to handle the exception. It must be preceded by try block which means we can't use catch block alone. It can be followed by finally block later.
finally :
The "finally" block is used to execute the necessary code of the program. It is executed whether an exception is handled or not.
throw :
The "throw" keyword is used to throw an exception.
throws :
The "throws" keyword is used to declare exceptions. It specifies that there may occur an exception in the method. It doesn't throw an exception. It is always used with method signature.
Some Scenarios of Java Exceptions :
1. A scenario where ArithmeticException occurs
If we divide any number by zero, there occurs an ArithmeticException.
int a=50/0; // ArithmeticException
2. A scenario where NullPointerException occurs
If we have a null value in any variable, performing any operation on the variable throws a NullPointerException.
String s=null;
System.out.println(s.length()); // NullPointerException
3. A scenario where NumberFormatException occurs
If the formatting of any variable or number is mismatched, it may result into NumberFormatException. Suppose we have a string variable that has characters; converting this variable into digit will cause NumberFormatException.
String s="abc";
int i=Integer.parseInt(s); // NumberFormatException
4. A scenario where ArrayIndexOutOfBoundsException occurs
When an array exceeds to it's size, the ArrayIndexOutOfBoundsException occurs. there may be other reasons to occur ArrayIndexOutOfBoundsException.
int a[]=new int[5];
a[10]=50; // ArrayIndexOutOfBoundsException
5. A scenario where FileNotFoundException occurs
When the specified file does not exist or cannot be accessed throws a FileNotFoundExeption.
File file = new File("newFile.txt");
FileReader fr = new FileReader(file); // FileNotFoundException
Example for ArithmeticException :
import java.lang.ArithmeticException;
public class ArithmeticExceptionHandling {
public static void main(String[] args) {
try {
int divideByZero = 5 / 0; // Division by zero will throw ArithmeticException
System.out.println(divideByZero); // This line won't be reached if exception occurs
}
catch (ArithmeticException e) {
System.out.println(e); // Print the exception message
}
}
}
In this example :
try Block :
catch Block :
Output :
2. Handle ArithmeticException using Finally Block :
import java.lang.ArithmeticException;
public class ArithmeticExceptionHandling {
public static void main(String[] args) {
try {
int divideByZero = 5 / 0; // Division by zero will throw ArithmeticException
System.out.println(divideByZero); // This line won't be reached if exception occurs
}
catch (ArithmeticException e) {
System.out.println(e); // Print the exception message
}
finally {
System.out.println("This is the finally block"); // Executes regardless of exception
}
}
}
In this example :
try Block :
catch Block :
finally Block :
3. Handle ArithmeticException using throws keyword :
import java.lang.ArithmeticException;
public class ArithmeticExceptionHandling {
public static void main(String[] args) {
try {
int divideByZero = divide(5, 0); // Calling divide method which may throw ArithmeticException
System.out.println("Result: " + divideByZero);
}
catch (ArithmeticException e) {
System.out.println(e);
}
}
public static int divide(int dividend, int divisor) throws ArithmeticException {
return dividend / divisor;
}
}
In this example :
main Method :
divide Method :
Handling the Exception:
4. Handle ArithmeticException using throw Keyword :
import java.lang.ArithmeticException;
public class ArithmeticExceptionHandling {
public static void main(String[] args) {
try {
int divideByZero = divide(5, 0); // Calling divide method which may throw ArithmeticException
System.out.println("Result : " + divideByZero);
}
catch (ArithmeticException e) {
System.out.println(e);
}
}
public static int divide(int dividend, int divisor) {
if (divisor == 0) {
throw new ArithmeticException("Division by zero is not allowed");
}
return dividend / divisor;
}
}
Example for NullPointerException :
public class NullPointerExceptionHandling {
public static void main(String[] args) {
try {
String str = null;
System.out.println("Length of the string: " + str.length()); // This line will throw NullPointerException
}
catch (NullPointerException e) {
System.out.println(e); // Print the exception
}
}
}
In this example :
try Block :
catch Block :
2. Handle NullPointerException using finally block :
public class NullPointerExceptionHandling {
public static void main(String[] args) {
try {
String str = null;
System.out.println("Length of the string: " + str.length()); // This line will throw NullPointerException
}
catch (NullPointerException e) {
System.out.println(e); // Print the exception
}
finally {
System.out.println("This is the finally block"); // Executes regardless of exception
}
}
}
In this example :
try Block :
catch Block :
finally Block :
3. Handle NullPointerException using throws keyword :
public class NullPointerExceptionHandling {
public static void main(String[] args) {
try {
String str = null;
printStringLength(str); // Calling method that may throw NullPointerException
}
catch (NullPointerException e) {
System.out.println(e);
}
}
public static void printStringLength(String str) throws NullPointerException {
if (str == null) {
throw new NullPointerException("String is null"); // Throw NullPointerException explicitly
}
System.out.println("Length of the string: " + str.length());
}
}
In this example :
main Method :
printStringLength Method :
try-catch Block :
4. Handle NullPointerException using throw keyword :
public class NullPointerExceptionHandling {
public static void main(String[] args) {
try {
String str = null;
printStringLength(str); // Calling method that may throw NullPointerException
}
catch (NullPointerException e) {
System.out.println(e);
}
}
public static void printStringLength(String str) {
if (str == null) {
throw new NullPointerException("String is null"); // Throw NullPointerException explicitly
}
System.out.println("Length of the string: " + str.length());
}
}
In this example :
main Method :
printStringLength Method :
try-catch Block :
领英推荐
Example for NumberFormatException :
public class NumberFormatExceptionHandling {
public static void main(String[] args) {
String s = "abc"; // Invalid numeric string
try {
int num = Integer.parseInt(s); // Attempting to parse string to integer
System.out.println(num);
}
catch (NumberFormatException e) {
System.out.println(e);
}
}
}
In this example :
main Method :
try Block :
catch Block :
2. Handle NumberFormatException using finally block :
public class NumberFormatExceptionHandling {
public static void main(String[] args) {
String s = "abc"; // Invalid numeric string
try {
int num = Integer.parseInt(s); // Attempting to parse string to integer
System.out.println(num);
}
catch (NumberFormatException e) {
System.out.println(e);
} finally {
System.out.println("This is finally block"); // Executes regardless of exception
}
}
}
In this example :
main Method :
try Block :
catch Block:
finally Block :
3. Handle NumberFormatException using throws keyword :
public class NumberFormatExceptionHandling {
public static void main(String[] args) {
String s = "abc"; // Invalid numeric string
try {
int num = parseInteger(s); // Calling method that may throw NumberFormatException
System.out.println(num);
}
catch (NumberFormatException e) {
System.out.println(e); // Print the exception
}
}
public static int parseInteger(String s) throws NumberFormatException {
return Integer.parseInt(s); // Attempting to parse string to integer
}
}
In this example :
main Method :
try Block :
catch Block :
parseInteger Method :
4. Handle NumberFormatException using throw keyword :
public class NumberFormatExceptionHandling {
public static void main(String[] args) {
String s = "abc"; // Invalid numeric string
try {
int num = parseInteger(s); // Calling method that may throw NumberFormatException
System.out.println(num);
}
catch (NumberFormatException e) {
System.out.println(e);
}
}
public static int parseInteger(String s) throws NumberFormatException {
if (s == null || s.isEmpty()) {
throw new NumberFormatException("Input string is null or empty");
}
int result;
try {
result = Integer.parseInt(s); // Attempting to parse string to integer
}
catch (NumberFormatException e) {
throw new NumberFormatException("Failed to parse integer: " + s);
}
return result;
}
}
In this example :
main Method :
try Block :
catch Block :
parseInteger Method :
Example for ArrayIndexOutOfBoundException :
public class ArrayIndexOutOfBoundsExceptionHandling {
public static void main(String[] args) {
try {
int[] num = {5, 10, 20, 25, 50};
System.out.println(num[10]); // Trying to access an element outside the bounds of the array
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println(e); // Print the exception
}
}
}
In this example :
try Block :
catch Block :
2. Handle ArrayIndexOutOfBoundException using finally block :
public class ArrayIndexOutOfBoundsExceptionHandling {
public static void main(String[] args) {
try {
int[] num = {5, 10, 20, 25, 50};
System.out.println(num[10]); // Trying to access an element outside the bounds of the array
}
catch (ArrayIndexOutOfBoundsException e) {
System.out.println(e); // Print the exception
}
finally {
System.out.println("Finally block executed"); // Executes regardless of whether an exception occurred or not
}
}
}
try Block :
catch Block :
finally Block :
3. Handle ArrayIndexOutOfBoundException using throws keyword :
public class ArrayIndexOutOfBoundsExceptionHandling {
public static void main(String[] args) {
try {
int[] num = {5, 10, 20, 25, 50};
getElement(num, 10); // Calling method that may throw ArrayIndexOutOfBoundsException
}
catch (ArrayIndexOutOfBoundsException e) {
System.out.println(e); // Print the exception
}
}
public static int getElement(int[] array, int index) throws ArrayIndexOutOfBoundsException {
return array[index]; // Accessing array element which may throw ArrayIndexOutOfBoundsException
}
}
In this example :
try Block :
catch Block :
getElement Method :
4. Handle ArrayIndexOutOfBoundException using throw keyword :
public class ArrayIndexOutOfBoundsExceptionHandling {
public static void main(String[] args) {
try {
int[] num = {5, 10, 20, 25, 50};
getElement(num, 10); // Calling method that may throw ArrayIndexOutOfBoundsException
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println(e); // Print the exception
}
}
public static int getElement(int[] array, int index) {
if (index < 0 || index >= array.length) {
throw new ArrayIndexOutOfBoundsException("Index " + index + " is out of bounds for array of length " + array.length);
}
return array[index]; // Accessing array element which may throw ArrayIndexOutOfBoundsException
}
}
In this example :
try Block :
catch Block :
getElement Method :
Example for FileNotFoundException :
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
public class FileNotFoundExceptionHandling {
public static void main(String[] args) {
try {
File newFile = new File("newFile.txt");
FileInputStream stream = new FileInputStream(newFile);
}
catch(FileNotFoundException e) {
System.out.println(e);
}
}
}
In this example :
try Block :
catch Block :
2. Handle FileNotFoundException using finally block :
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
public class FileNotFoundExceptionHandling {
public static void main(String[] args) {
try {
File newFile = new File("newFile.txt");
FileInputStream stream = new FileInputStream(newFile);
}
catch(FileNotFoundException e) {
System.out.println(e); // Print the exception
}
finally {
System.out.println("This is finally block"); // Executes regardless of whether an exception occurred or not
}
}
}
In this example :
try Block :
catch Block :
finally Block :
3. Handle FileNotFoundException using throws keyword :
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
public class FileNotFoundExceptionHandling {
public static void main(String[] args) {
try {
openFile("newFile.txt");
}
catch (FileNotFoundException e) {
System.out.println(e); // Print the exception
}
}
public static void openFile(String filename) throws FileNotFoundException {
File newFile = new File(filename);
FileInputStream stream = new FileInputStream(newFile);
System.out.println("File opened successfully: " + newFile.getName());
}
}
In this example :
main Method :
openFile Method :
throws Keyword :
4. Handle FileNotFoundException using throw keyword :
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
public class FileNotFoundExceptionHandling {
public static void main(String[] args) {
try {
openFile("newFile.txt"); // Attempting to open a file named "newFile.txt"
} catch (FileNotFoundException e) {
System.out.println(e);
}
}
public static void openFile(String filename) throws FileNotFoundException {
File newFile = new File(filename); // Creating a File object with the specified filename
if (!newFile.exists()) {
throw new FileNotFoundException("File '" + filename + "' not found"); // Throw FileNotFoundException explicitly
}
FileInputStream stream = new FileInputStream(newFile); // Attempting to create a FileInputStream
System.out.println("File opened successfully: " + newFile.getName());
}
}
In this example :
main Method :
openFile Method :