Ch 12 · Exception Handling · Java
Topic 12 of 13 in Java — Complete Tutorial (Beginner) — 2 lessons.
try / catch / finally
Programs face unpredictable problems at runtime: dividing by zero, accessing a missing array index, or invalid input. In Java these are called exceptions, and if unhandled they crash the program. The try/catch block lets you handle them gracefully: risky code goes in try, and if an exception occurs Java jumps to catch, where you decide how to respond. The optional finally block always runs, error or not — ideal for cleanup.
Throwing Exceptions
You can deliberately signal an error with the throw keyword, creating an exception with a clear message. This is essential for validating input: when a method receives data that breaks its rules, throwing immediately makes the problem visible instead of letting bad data spread. A descriptive message — "Age must be between 5 and 25, but got -3" — tells exactly what went wrong, the mark of a thoughtful programmer.