java / beginner
Snippet
Basic Try-Catch Block
The try-catch statement handles errors gracefully. If an error occurs inside the try block, the program jumps to the catch block instead of crashing.
snippet.java
1
2
3
4
5
6
try {String text = null;int len = text.length();} catch (Exception e) {System.out.println("Error caught");}
Breakdown
1
try {
Begins a protected block where the code is monitored for exceptions.
2
int len = text.length();
This line will fail because 'text' is null, triggering the catch block.
3
catch (Exception e) {
Defines the block that handles the error if one is thrown.