When executing a method that may encounter issues during runtime, we need proper exception handling mechanisms. Exceptions halt program execution, so we must use try-catch blocks to handle these scenarios gracefully.
Here's an example demonstrating basic exception handling:
public static void main(String[] args) {
try {
new DivisionExample().divideNumbers(5, 0);
} catch (ArithmeticException error) {
// Since division by zero results in ArithmeticException,
// the caught exception type matches accordingly
System.out.println("Calculation error occurred: " + error.getMessage());
} finally {
// This block executes regardless of whether an exception occurs
System.out.println("Cleaning up resources");
}
}
}
</div>A commmon question arises: if both the base Exception class and specific subclasses can catch exceptions, why not always use the top-level Expection class? The answer lies in handling different types of exceptions with specialized responses.
Consider this multi-catch scenario:
<div>```
try {
new DivisionExample().divideNumbers(8, 0);
} catch (ArithmeticException arithmeticError) {
System.out.println("Mathematical operation failed: " + arithmeticError.getMessage());
} catch (IllegalArgumentException argumentError) {
// This won't execute since the actual exception isn't IllegalArgumentException
System.out.println("Invalid argument provided");
} catch (Exception generalError) {
System.out.println("General error occurred: " + generalError.getMessage());
} finally {
System.out.println("Final cleanup operations");
}
// Note that catch blocks work like if-else statements,
// requiring specific exceptions before general ones
private String errorCode;
public CustomBusinessException(String message, String code) {
super(message);
this.errorCode = code;
}
// Override appropriate methods as needed
@Override
public String getMessage() {
return "Custom Error [" + errorCode + "]: " + super.getMessage();
}
}
</div>Implementing the custom exception:
<div>```
// Method declaration must specify the custom exception
int performDivision(int dividend, int divisor) throws CustomBusinessException {
if (divisor == 0) {
// Throw the custom exception when conditions aren't met
throw new CustomBusinessException(
"Division by zero is not allowed",
"DIV_BY_ZERO_001"
);
}
return dividend / divisor;
}
// Usage in try-catch block
try {
result = performDivision(10, 0);
} catch (CustomBusinessException customError) {
System.out.println("Business rule violation: " + customError.getMessage());
}