Overview:
Lesson 2 Try-Catch Blocks dives deeper into the practical aspects of exception handling by exploring the use of try-catch
blocks. These blocks are fundamental for handling exceptions in Java, allowing developers to gracefully manage errors and unexpected situations in their code.
ey Concepts:
- Try-Catch Blocks:
- Definition: A
try-catch
block is used to enclose a section of code where exceptions may occur. Thetry
block contains the code that might throw an exception, and thecatch
block handles the exception if one occurs. - Purpose: Provides a structured way to handle exceptions, preventing them from causing the program to terminate abruptly.
- Definition: A
- Throwing Exceptions:
- Definition: Throwing an exception is a way to indicate that an abnormal condition has occurred during the execution of a program. This is done using the
throw
keyword. - Purpose: Allows developers to signal and handle errors in a controlled manner.
- Definition: Throwing an exception is a way to indicate that an abnormal condition has occurred during the execution of a program. This is done using the
Example:
Let’s create a program that demonstrates the use of try-catch
blocks for exception handling. We’ll use a custom exception and throw it within a try
block, then catch and handle the exception in the catch
block.
import java.util.Scanner;
// Custom exception for handling negative values
class NegativeValueException extends Exception {
public NegativeValueException(String message) {
super(message);
}
}
public class TryCatchExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
try {
System.out.print("Enter a positive number: ");
int userInput = scanner.nextInt();
processInput(userInput);
} catch (NegativeValueException e) {
System.err.println("Error: " + e.getMessage());
} catch (Exception e) {
System.err.println("An unexpected error occurred: " + e.getMessage());
} finally {
scanner.close();
}
}
private static void processInput(int number) throws NegativeValueException {
if (number < 0) {
throw new NegativeValueException("Negative values are not allowed.");
}
System.out.println("You entered a positive number: " + number);
}
}
In this example, the processInput
method throws a NegativeValueException
if the user enters a negative number. The try-catch
block in the main
method catches this exception and provides an appropriate error message. This illustrates how to use try-catch
blocks for controlled exception handling, enhancing the robustness of your Java applications.