Java FAQ: Top Questions
15. How does exception handling work in Java?
Exception handling
in Java manages runtime errors, ensuring program reliability using
try
,
catch
,
finally
,
throw
, and
throws
.
-
try-catch:
Code that might throw an exception is placed in a
try
block; exceptions are caught incatch
blocks. - finally: Executes code (e.g., resource cleanup) regardless of whether an exception occurs.
- throw: Explicitly throws an exception.
- throws: Declares exceptions a method might throw.
-
Checked vs. Unchecked:
Checked exceptions (e.g.,
IOException
) must be handled or declared; unchecked (e.g.,NullPointerException
) need not.