Exceptions
Exceptions
When something goes wrong at runtime (e.g. file not found, invalid input), Java uses exceptions to signal the error. You can catch and handle them so the program does not crash, or let them propagate to the caller.
try and catch
Wrap risky code in a try block. If an exception is thrown, control jumps to a matching catch block:
javatry { int[] arr = { 1, 2, 3 }; System.out.println(arr[5]); // throws ArrayIndexOutOfBoundsException } catch (ArrayIndexOutOfBoundsException e) { System.out.println(\"Invalid index: \" + e.getMessage()); }
You can catch multiple exception types with separate catch blocks, or one catch (Exception e) for any exception (use sparingly).
Checked vs unchecked
- Unchecked exceptions (e.g.
NullPointerException,IllegalArgumentException) extendRuntimeException. You do not have to declare or catch them. - Checked exceptions (e.g.
IOException) must be either caught or declared in the method signature withthrows:
javapublic void readFile() throws IOException { // code that may throw IOException }
Callers of this method must either catch IOException or declare throws as well.
throw and finally
- Use
throw new SomeException(\"message\")to throw an exception yourself. - A
finallyblock runs after the try (and catch, if any), whether or not an exception was thrown. Use it for cleanup (e.g. closing a file or connection).
javatry { // use resource } catch (IOException e) { // handle } finally { // always runs; close resources here }
In interviews you may be asked about exception hierarchy, when to use checked vs unchecked, and how to design APIs that throw meaningful exceptions.