Exception Handling
Exceptions are Runtime Errors.
There are many types of errors:
Syntax Error - can be removed with the help of compiler.
Logical Error - can be removed with the help of debugger.
Runtime Error - can be resolved with the help of Exception Handling.
Causes of runtime errors are bad input or unavailability of resources.
Exception handling is process of responding to the runtime errors.
Syntax and Logical errors are faced by Programmers, and Runtime errors are faced by User.
Built-in Exception Classes
Object is the parent class for all the java classes.
Exception is the parent class for all the exceptions.
Exception Class Methods:
Exception classes are categorized into two types:
Checked exceptions must be handled by
tryandcatch, java compiler forces you to writetryandcatch.Unchecked exceptions are not mandatory to be handled.
Only Runtime Exceptions are the unchecked exceptions.
Custom Exception Classes
Propagation of Exception
Output:
Even though, the exception occurred in method1(), It was passed on to its calling methods, and finally was handled in main().
Throw
throw keyword is used to throw an exception logically.
Only one exception can be thrown at a time by using throw keyword.
We can catch the exception in the same function using try and catch block.
Throws
throws keyword is used to pass the exception to the calling function.
throws is used for declaring that a method may throw exception.
Firstly we generated exception in area(), But we don't want to handle it inside that function...
So we pass it on to the calling function using throws keyword in the function name.
finally Block
finally keyword is used in association with a try/catch block.
finally keyword is meant to execute whether an exception occurs or not.
Usually finally block is used to release the resources.
Output:
Here, we haven't handled the particular exception, but still the finally block was executed.
Try with resources
Garbage Collector only releases the heap memory (Heap memory is resource).
Programmer is responsible for releasing the other resources (Network, Database, Files).
This is a proper code, to handle resources.
But, we has to use finally block everytime, to close the acquired resources.
To avoid finally block, we can use try with resources.
try with resources, automatically closes the resources.
try block wil automatically release the acquired resources after it finishes its execution.