Exception handling in Java allows us to deal with errors that occur during the execution of our program. When an exception occurs, the Java Virtual Machine
There are two types of exceptions in Java:
Checked exceptions: At compile time, these exceptions are checked for validity. If a code segment within a method throws a checked exception, the method must either handle the exception or explicitly declare it using throws
.
Unchecked exceptions: Unlike checked exceptions, these exceptions do not require explicit handling or declaration. They can occur at runtime and are not enforced by the compiler.
try-catch
blockThe try
-catch
statement is used to handle exceptions in Java. The try
block contains the code we are trying to execute, and the catch
block contains the code that will be executed if an exception is thrown.
public class ExceptionHandlingExample {public static void main(String[] args) {try {// Code that may throw an exceptionint result = divide(10, 0);System.out.println("Result: " + result);} catch (ArithmeticException e) {// Exception handling codeSystem.out.println("An error occurred: " + e.getMessage());}}// Method that performs divisionpublic static int divide(int numerator, int denominator) {return numerator / denominator;}}
Line 1–2: The code begins with the declaration of a public class named ExceptionHandlingExample
and its main
.
Line 3: The try
block contains the code that might throw an exception.
Line 5: Inside the try
block, the code attempts to perform a division operation by calling the divide()
method with arguments 10
and 0
.
Line 7–10: The catch block starts, specifying that it will catch an ArithmeticException
if it occurs within the try block.
Line 14–16: The divide()
method is declared, which takes two integer parameters: numerator
and denominator
. Inside the method, the division operation numerator / denominator
is performed, and the result is returned as the method's output.
finally
blockThe finally
block is an optional block in Java that executes code regardless of whether or not an exception is thrown. It ensures that specific code is executed, providing a guarantee of execution even in the presence of exceptions.
public class Finally{public static void main(String[] args) {int result = divideNumbers(10, 0);System.out.println("Result: " + result);}public static int divideNumbers(int dividend, int divisor) {try {return dividend / divisor;} catch (ArithmeticException e) {System.out.println("Error: " + e.getMessage());return 0;} finally {System.out.println("Finally block executed.");}}}
Line 1: The code begins with the declaration of a public class named Finally
.
Line 2–4: The code attempts to perform a division operation by calling the divideNumbers
method with arguments 10
and 0
.
Line 7: The divideNumbers
method is declared, which takes two integer parameters - dividend
and divisor
.
Line 8–9: The try block contains the division operation dividend / divisor
.
Line 10–15: If an ArithmeticException
is caught, the code within the catch block is executed. It prints an error message to the console using the System.out.println
statement. The error message prints out the error message obtained from the caught exception, e.getMessage()
. It then returns 0
.
throw
keywordThe throw
keyword in Java is used to manually throw an exception. When the throw
statement is executed, it interrupts the normal flow of the program and transfers control to the nearest matching catch
block or, if none is found, terminates the program.
public class Throw {public static void main(String[] args) {try {validateAge(15);} 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 at least 18");}// Additional code if age is validSystem.out.println("Age is valid.");}}
Line 1: The code begins with the declaration of a public class named Throw
.
Line 3–9: The main method is defined as the entry point of the program.
Line 4: The code calls the validateAge
method with the argument 15
.
Line 5–7: It specifies that it will catch an IllegalArgumentException
within the try block.
Line 10: The validateAge
method is declared, which takes an integer parameter age
. Inside the method, there is an if condition to check if age
is less than 18
.
Line 12: If the age
is less than 18
, the code throws a new IllegalArgumentException
.
Line 15: If the age
is valid (i.e., not less than 18), the code after the if condition is executed. In this case, it prints "Age is valid."
to the console.
Free Resources