Basic Try-Catch in Java
beginner· Exceptions · Error Handling
Problem
A try block wraps code that might fail, and a matching catch block runs in its place if that specific kind of failure actually happens, instead of the program crashing.
Throw an exception inside a try block and handle it with a matching catch block.
Input
none
Output
Caught: Something went wrong
Java Program
Java
public class BasicTryCatch {
public static void main(String[] args) {
try {
throw new Exception("Something went wrong");
} catch (Exception e) {
System.out.println("Caught: " + e.getMessage());
}
}
}Output
Caught: Something went wrong
Core Logic
Placing a throw statement inside a try block, with a catch block declared for that exception's type right after it, is the entire mechanism — nothing more is needed to intercept a failure.
How It Works
- 1The
tryblock contains a singlethrow new Exception("Something went wrong"), so it always fails on purpose here. - 2As soon as
throwruns, control jumps immediately out of thetryblock — any code after the throw statement never executes. - 3
catch (Exception e)matches the thrown exception's type and runs instead, receiving the exception object ase. - 4
e.getMessage()returns the text that was passed to the exception's constructor when it was thrown.
The thrown exception carries the message "Something went wrong", which the catch block reads back and prints as "Caught: Something went wrong".
💡
Key Point: Nothing after a throw statement in the same block ever runs — control transfers to the matching catch immediately, which is what makes try-catch different from an ordinary if-check.
Key Concepts
try blockcatch blockthrow statement