- hardware failures,
- resource exhaustion, and
- improper coding.
Exception handling works by transferring the execution of a program to an appropriate exception handler when an exception occurs.
For example, if you call a method that opens a file but the file cannot be opened, execution of that method will stop, and the code that you wrote to deal with this situation will be run. Therefore, we need a way to tell the JVM what code to execute when a certain exception happens.
To do this, we use the try and catch keywords. The try is used to define a block of code in which exceptions may occur. This block of code is called a guarded region (which really means "risky code goes here"). One or more catch clauses match a specific exception (or group of exceptions) to a block of code that handles it.