⬅ Previous Topic
Exceptions in JavaNext Topic ⮕
Java catch Multiple Exceptions⬅ Previous Topic
Exceptions in JavaNext Topic ⮕
Java catch Multiple ExceptionsIn real-world programming, not everything goes as planned. Files might be missing, users might enter invalid input, or network calls might fail. In Java, rather than allowing your program to crash, you can use try-catch
blocks to gracefully handle exceptions.
The try-catch
block is Java's way of saying: "Try this risky thing, and if it fails, here's what to do." It helps you prevent unexpected termination of your program by catching exceptions and letting you handle them in a user-friendly way.
try {
// Code that may throw an exception
} catch (ExceptionType e) {
// Code to handle the exception
}
This is one of the most common runtime exceptions. Let’s see how try-catch
can help handle it:
public class TryCatchExample {
public static void main(String[] args) {
int a = 10;
int b = 0;
try {
int result = a / b;
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero!");
}
System.out.println("Program continues...");
}
}
Cannot divide by zero!
Program continues...
The division a / b
throws an ArithmeticException
because b
is 0. Without the try-catch
, the program would crash. But thanks to the catch block, we handle it and continue execution.
Sometimes, more than one type of exception might occur. You can handle each differently:
public class MultipleCatchExample {
public static void main(String[] args) {
try {
int[] arr = new int[3];
arr[5] = 100 / 0;
} catch (ArithmeticException e) {
System.out.println("Arithmetic error occurred.");
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array index is out of bounds.");
} catch (Exception e) {
System.out.println("General exception caught.");
}
}
}
Array index is out of bounds.
Java checks the catch
blocks in the order they are written. If you place a general Exception
block before specific exceptions like ArithmeticException
or ArrayIndexOutOfBoundsException
, the specific ones will never be reached, causing a compilation error.
You can get more details about what went wrong by printing the exception object:
public class ExceptionMessageExample {
public static void main(String[] args) {
try {
String str = null;
System.out.println(str.length());
} catch (NullPointerException e) {
System.out.println("Exception: " + e);
e.printStackTrace();
}
}
}
Exception: java.lang.NullPointerException
java.lang.NullPointerException
at ExceptionMessageExample.main(...)
finally
block (covered in another tutorial) for cleanup actions.Imagine trying to read from a file that doesn’t exist:
import java.io.*;
public class FileExample {
public static void main(String[] args) {
try {
FileReader reader = new FileReader("nonexistent.txt");
reader.read();
reader.close();
} catch (FileNotFoundException e) {
System.out.println("File not found.");
} catch (IOException e) {
System.out.println("Error reading the file.");
}
}
}
File not found.
The try-catch
block is your first line of defense against unpredictable runtime errors. It's not just about avoiding crashes; it's about writing robust, user-friendly Java applications that fail gracefully — or, better yet, recover intelligently.
try
block and there is no matching catch
block provided?catch (Exception e)
block before specific ones like catch (ArithmeticException e)
leads to a compile-time error.try {
int[] arr = new int[2];
arr[4] = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Arithmetic exception occurred.");
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Index out of bounds.");
}
NullPointerException
?
try {
String str = null;
System.out.println(str.length());
} catch (NullPointerException e) {
System.out.println("Caught a null pointer!");
}
⬅ Previous Topic
Exceptions in JavaNext Topic ⮕
Java catch Multiple ExceptionsYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.