Exceptions Handling Fundamentals
When there is an exception, the user data may be corrupted. This should be tackled by the programmer by carefully designing the program.
How do you handle exceptions?
Java exception handling is managed via five keywords: try, catch, throw, throws & finally
- Try block: contains the program statements that you want to monitor for exceptions
- Catch: you can catch an exception using this & handle it in some time manner
- Throw: used to manually throw an error
- Throws: Any exception that is thrown out of a method must be specified as such by a throws clause
- Finally: Any code that absolutely must be executed after try block completes is put in a finally block
- We write the block of statements which arises the exception at run time inside try block, the normal code logic is placed inside a block of code starting with the “try” keyword
- We write the block of statements which will generates user friendly error messages inside catch block.
- Finally block is optional.This block contains code that is ALWAYS executed, either after the “try” block code or after the “catch” block code
- Finally blocks can be used for operations that must happen no matter what (i.e. cleanup operations such as closing a file)
- Exception handling has 2 benefits: First, it allows you to fix the error and secondly, it prevents the program from automatically terminating.