Lesson 16 of 20
Exception Handling
Exception Handling
Java uses exceptions to handle errors at runtime. When something goes wrong, an exception is thrown, and you can catch it to handle it gracefully.
try / catch / finally
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Error: " + e.getMessage());
} finally {
System.out.println("This always runs");
}
try— wraps code that might throw an exceptioncatch— handles a specific exception typefinally— always executes, whether an exception occurred or not (useful for cleanup)
Checked vs Unchecked Exceptions
- Unchecked (
RuntimeExceptionand its subclasses):NullPointerException,ArithmeticException,ArrayIndexOutOfBoundsException. The compiler does not force you to handle these. - Checked (
Exceptionbut notRuntimeException):IOException,SQLException. The compiler forces you to either catch them or declare them withthrows.
Throwing Exceptions
Use throw to raise an exception yourself:
void setAge(int age) {
if (age < 0) {
throw new IllegalArgumentException("Age cannot be negative");
}
}
Custom Exceptions
You can define your own exception classes by extending Exception (checked) or RuntimeException (unchecked):
class InsufficientFundsException extends RuntimeException {
private double deficit;
InsufficientFundsException(double deficit) {
super("Insufficient funds: need " + deficit + " more");
this.deficit = deficit;
}
double getDeficit() { return deficit; }
}
Your Task
Create a static inner class SafeCalculator with:
static String divide(int a, int b)— returns the result as a string, or"Error: division by zero"ifbis 0 (use try/catch onArithmeticException)static String parseAndAdd(String x, String y)— parses both strings as integers and returns their sum as a string. If either string is not a valid integer, return"Error: invalid number". Use afinallyblock to print"parse complete"regardless of outcome.
Also create a custom exception class NegativeNumberException (extending RuntimeException) with a constructor that takes a String message, and a method:
static int squareRoot(int n)— ifn < 0, throwNegativeNumberExceptionwith message"negative input: "followed byn. Otherwise return(int) Math.sqrt(n).
Then run the test sequence shown in the expected output.
TeaVM (WASM) loading...
Loading...
Click "Run" to execute your code.