✅ 1. If it’s a checked or unchecked exception thrown from run()
:
- The thread terminates immediately.
- The exception is not rethrown to the main thread.
- If uncaught, it’s passed to the thread’s UncaughtExceptionHandler (if any).
📦 Example:
Thread t = new Thread(() -> {
System.out.println("Running...");
throw new RuntimeException("Something went wrong!");
});
t.start();
🧨 Output:
Running...
Exception in thread "Thread-0" java.lang.RuntimeException: Something went wrong!
at ...
The thread crashes.
Other threads (like main
) continue running.
🤔 What If I Try to Catch the Exception in main()
?
try {
Thread t = new Thread(() -> {
throw new RuntimeException("Boom!");
});
t.start();
} catch (Exception e) {
System.out.println("Caught in main!"); // ❌ won't happen
}
❌ Does not work!
Exceptions thrown in one thread don’t propagate to another thread (like main
).
✅ How to Handle It Properly
🛡 1. Catch exceptions inside the thread
Thread t = new Thread(() -> {
try {
System.out.println("Thread working...");
throw new RuntimeException("Oops!");
} catch (Exception e) {
System.out.println("Caught in thread: " + e.getMessage());
}
});
t.start();
🧯 2. Use Thread.setUncaughtExceptionHandler
This is like a global “oops catcher” for a thread.
Thread t = new Thread(() -> {
throw new RuntimeException("Boom!");
});
t.setUncaughtExceptionHandler((thread, ex) -> {
System.out.println("Thread " + thread.getName() + " crashed: " + ex.getMessage());
});
t.start();
🧠 You can also set a default for all threads:
Thread.setDefaultUncaughtExceptionHandler((t, e) -> {
System.out.println("Unhandled in thread " + t.getName() + ": " + e.getMessage());
});
🚀 What About Callable and Future?
If you’re using Callable
with ExecutorService
, the exception is wrapped inside a Future
.
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<String> future = executor.submit(() -> {
throw new IllegalStateException("Error inside task");
});
try {
future.get(); // throws ExecutionException
} catch (ExecutionException e) {
System.out.println("Caught: " + e.getCause()); // prints original exception
}
✅ Summary
Situation | What Happens |
---|---|
Exception in Thread.run() | Thread terminates |
Exception not caught | Sent to UncaughtExceptionHandler |
Try-catch in main thread? | ❌ Doesn’t catch child thread exceptions |
Callable submitted to executor | Exception is wrapped in ExecutionException |
Best practice | Catch inside thread or set handler |