When does things go wrong?
- User Input → Enter invalid inputs
- Device Errors → Printer jams, network connection drops.
- Resource Limitations → Disk Full
- Code Errors→ Invalid array index, key not present in hash table, refer to a variable that is
null
, divide by zero,…
- What can be an idea of signaling errors:
- One way: Return an invalid value. Example → return
-1
at end of file
- But what if there is no obvious invalid value? → Example, return 0 (as false) if item is not found, but item can also be found at index 0.
Exception Handling
- Code that generates error is conventionally said to → raise an exception or throw an exception.
- Should also notify the type of error when raising this exception:
- Information about the nature of the exception.
- So it is natural to structure an exception as an object.
- Caller catches the exception and takes corrective action.
- Extract information about the error from the exception object.
- Graceful interruption rather than program crash.
- If caller does not catch the error:
- It passes back up the calling chain → Error is passed to the person who called the caller.
- Declare if a method can throw an exception(raise an exception):
- Compiler can then check whether the calling code has made some provisions to handle this exception.
Java’s Classification of Errors
<aside>
💡 All exceptions descend from the class Throwable.
</aside>
- Two branches from Throwable → Error and Exception.
- Error → Relatively rare → Not the programmer’s fault.
- Internal errors, resource limitations within Java Runtime.
- No realistic correction action is possible, notify the caller and terminate gracefully.
- Exception→ Has two sub branches.
- Runtime Exceptions and Checked Exceptions