The following code example demonstrates How to Perform Exception Handling in Java.
try-catch
Basically, we use this block to catch and handle exceptions.
public class TryCatchExample {
public static void main(String[] args) {
try {
int result = divide(10, 0); // This will throw an ArithmeticException
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Exception caught: " + e.getMessage());
}
}
public static int divide(int dividend, int divisor) {
return dividend / divisor;
}
}
In this example, we attempt to divide by zero, which results in an ArithmeticException
. Indeed, we catch this exception in the catch
block and handle it.
throw
We use the throw keyword to manually throw an exception. For example.
public class ThrowExample {
public static void main(String[] args) {
try {
validateAge(15); // This will throw an IllegalArgumentException
} catch (IllegalArgumentException e) {
System.out.println("Exception caught: " + e.getMessage());
}
}
public static void validateAge(int age) {
if (age < 18) {
throw new IllegalArgumentException("Age must be 18 or older");
}
System.out.println("Age is valid");
}
}
In this example, we manually throw an IllegalArgumentException
if the age is less than 18.
throws
We use the throws keyword in method signatures to indicate that a method may throw certain exceptions. For example.
public class ThrowsExample {
public static void main(String[] args) {
try {
readFile("nonexistent.txt"); // This may throw a FileNotFoundException
} catch (FileNotFoundException e) {
System.out.println("Exception caught: " + e.getMessage());
}
}
public static void readFile(String filename) throws FileNotFoundException {
// Code to read a file (may throw FileNotFoundException)
// ...
throw new FileNotFoundException("File not found");
}
}
Here, the readFile
method is declared with throws FileNotFoundException
in its signature, indicating that it may throw this exception.
finally
Similarly, we use the finally keyword to define a block of code that will be executed regardless of whether an exception is thrown or not. For example.
public class FinallyExample {
public static void main(String[] args) {
try {
int result = divide(10, 2); // This will not throw an exception
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Exception caught: " + e.getMessage());
} finally {
System.out.println("Finally block executed");
}
}
public static int divide(int dividend, int divisor) {
return dividend / divisor;
}
}
In this example, the finally
block will always be executed, whether or not an exception occurs.
To summarize, these examples illustrate the use of try
, catch
, throw
, throws
, and finally
in Java for exception handling.
Further Reading
Spring Framework Practice Problems and Their Solutions
From Google to the World: The Story of Go Programming Language
Why Go? Understanding the Advantages of this Emerging Language
Creating and Executing Simple Programs in Go