An exception is an error that happens while a program runs, such as reading a file that does not exist. Java gives you a clear way to catch these errors and decide what to do next.
try, catch and finally
Put the risky code in a try block. Handle a specific error in a catch block. Use finally for clean-up that must always run, such as closing a connection.
Checked and unchecked exceptions
- Checked: the compiler makes you handle them, such as IOException.
- Unchecked: usually caused by a bug, such as NullPointerException. Fix the cause rather than only catching it.
Good habits
- Catch the most specific exception you can, not a general Exception.
- Never leave a catch block empty. Log the error at least.
- Use try-with-resources so files and connections close automatically.
Custom exceptions
Create your own exception class when a business rule fails, such as InsufficientBalanceException. It makes the error clear to anyone reading the code.
Next step: see our Java Full Stack course at ScholarLogic, or book a free demo class. A counsellor will share the fee and the next batch dates.
