Java ProgramsExceptionsBasic Try-Catch

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
  1. 1The try block contains a single throw new Exception("Something went wrong"), so it always fails on purpose here.
  2. 2As soon as throw runs, control jumps immediately out of the try block — any code after the throw statement never executes.
  3. 3catch (Exception e) matches the thrown exception's type and runs instead, receiving the exception object as e.
  4. 4e.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

Related Programs