capypad
0 day streak
java / beginner
Snippet

Basic Exception Handling

Java uses try-catch blocks to handle runtime errors (exceptions). This prevents the program from crashing by providing a way to respond to the error gracefully.

snippet.java
java
1
2
3
4
5
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero!");
}
Breakdown
1
try { ... }
Wraps code that might throw an exception.
2
catch (ArithmeticException e)
Specifies the type of error to catch and handle.
3
System.out.println(...);
Executes this block only if the error occurs.