Skip to main content

Exception Handling

What is Exception

An exception is a special event, which is raised during the execution of a program at runtime, that brings the execution to a halt. The reason for the exception is the unexpected behaviour of a statement which stops the execution.

What is Exception Handling

so now we know that exceptions are very common in program no matter how good your code is but it can behave differently on different situation/input hance we need the handle the exception so that we can prevent our execution to be stopped.

Types of Exception

Checked Exceptions

Checked exceptions are exceptions that must be declared or caught in the code. They are typically used for exceptional conditions that are expected to occur and should be handled explicitly.

  • in Checked exceptions we have to handle the exception otherwise compiler will show the error
  • in below code we have to handle SQLException otherwise it will give compile time error
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class DatabaseConnectionExample {
// this function determines that if there is problem in database connection then it will raise SQLException
public static void establishConnection(String url) throws SQLException {
Connection connection = DriverManager.getConnection(url);
System.out.println("Database connected successfully");
connection.close();
}

public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/mydatabase";

try {
establishConnection(url);// as this function explicitly mention that it can throw SQLException so we have to handle this
} catch (SQLException e) {
System.out.println("Error: Failed to establish a database connection.");
e.printStackTrace();
}
}
}

Unchecked exceptions

Unchecked Exceptions also known as runtime exceptions, are exceptions that do not need to be explicitly declared or caught. They often represent programming errors or unexpected conditions. These exceptions can occur anywhere in the code and propagate up the call stack if not caught.

  • Null Pointer Exception is an unchecked exception because it does not require explicit handling, and its occurrence is typically a result of programming errors or unexpected null values.
public class NullPointerExceptionExample {
public static void main(String[] args) {
String[] strings = { "Hello", null, "World" };

for (String str : strings) {
try {
int length = str.length(); // Accessing length of a null reference
System.out.println("Length: " + length);
} catch (NullPointerException e) {
System.out.println("Error: Null pointer exception.");
}
}
}
}


Example for exception handling with try-catch


public class Main {
public static double divideWithoutExceptionHandling(int numerator,int denominator){
double result = (double) (numerator/denominator);
return result;
}
public static double divideWithExceptionHandling(int numerator,int denominator){
try{
// so here a programmer have a idea that input can be wrong so we have to handle
double result = (double) (numerator/denominator);
}catch (ArithmeticException e){
System.out.println("exception occur: "+e);
}
return -1;
}
public static void main(String[] argv){
double res1 = divideWithExceptionHandling(2,0);
double res2 = divideWithoutExceptionHandling(2,0);
}
}

Concept of multiple catch block

  • the exception which occurs first in code block is raised.
  • All catch blocks must be ordered from most specific to most general, i.e. catch for ArithmeticException must come before catch for Exception.
public class Main {
public static void main(String[] argv){
try{
int[] arr = {1,2,3};
int val = arr[3];//try by commenting this
int res = 4/0;
}catch (ArithmeticException e) {
System.out.println("run when arithmetic exception found");
}catch (ArrayIndexOutOfBoundsException e){
System.out.println("run when index bigger then equal to size of array");
}catch (Exception e){
System.out.println("general exception: "+e);
}
}
}