Advertisement

Google Ad Slot: content-top

Java Exception


Exception handling in Java is a mechanism that allows you to handle runtime errors so that normal program flow is not disrupted. It helps prevent unexpected crashes and improves application stability.

What is an Exception?

An exception is an unwanted or unexpected event that occurs during program execution. It disrupts the normal flow of instructions.

Types of Exceptions

  • Checked Exceptions (Compile-time)
  • Exceptions checked by the compiler.
  • Example: IOException, SQLException
  • Unchecked Exceptions (Runtime)
  • Occur at runtime and are not checked at compile-time.
  • Example: NullPointerException, ArithmeticException
  • Errors (System failures)
  • Related to system failures and cannot be handled.
  • Example: OutOfMemoryError, StackOverflowError



Exception Handling Keywords:

Java provides five keywords for exception handling:

Keyword

Description

try

Defines a block of code to test for exceptions.

catch

Handles the exception if one occurs.

finally

A block that executes always, whether an exception occurs or not.

throw

Used to manually throw an exception.

throws

Declares exceptions that a method might throw.


Basic try-catch Example

public class Main {
public static void main(String[] args) {
try {
int result = 10 / 0; // This will cause ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero!");
}
System.out.println("Program continues...");
}
}
Try it yourself

Multiple catch Example:

You can handle different exceptions separately using multiple catch blocks.

public class Main {
public static void main(String[] args) {
try {
int arr[] = new int[5];
arr[10] = 50; // This will cause ArrayIndexOutOfBoundsException
} catch (ArithmeticException e) {
System.out.println("Arithmetic Exception occurred.");
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array Index Out of Bounds!");
} catch (Exception e) {
System.out.println("Some other exception occurred.");
}
}
}
Try it yourself

finallyBlock (Always Executes)

The finally block always executes whether an exception occurs or not.

public class Main {
public static void main(String[] args) {
try {
int data = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Exception caught.");
} finally {
System.out.println("Finally block executed.");
}
}
}
Try it yourself

Using throw to Manually Throw an Exception:

public class Main {
static void checkAge(int age) {
if (age < 18) {
throw new ArithmeticException("Not eligible to vote.");
} else {
System.out.println("You can vote!");
}
}

public static void main(String[] args) {
checkAge(16);
}
}
Try it yourself

Using throws to Declare Exceptions

If a method does not handle an exception, it can declare it using throws.

import java.io.*;

public class Main {
static void readFile() throws IOException {
FileReader file = new FileReader("file.txt");
file.read();
file.close();
}

public static void main(String[] args) {
try {
readFile();
} catch (IOException e) {
System.out.println("File not found.");
}
}
}

Try it yourself

Custom Exception (User-Defined Exception):

You can create your own exception class by extending Exception.

class MyException extends Exception {
MyException(String message) {
super(message);
}
}

public class Main {
static void validate(int age) throws MyException {
if (age < 18) {
throw new MyException("Age is less than 18.");
} else {
System.out.println("Valid Age.");
}
}

public static void main(String[] args) {
try {
validate(16);
} catch (MyException e) {
System.out.println("Caught Exception: " + e.getMessage());
}
}
}
Try it yourself