Lets elaborate on what we said above.We can connect on FB for more learning!!
How to catch exceptions?
Try Block:-This block is placed around the code that might generate an exception. Therefore try block is one that is used to wrap the exception prone code inside it,making our code protected.
Catch block:- This part have the declaration of the type of exception we are trying to catch. Here we can code for what action need to be taken on exception (Say publishing the error trace or giving error message to user)
ExceptionType:- declares the type of exception that the handler can handle.
name:-The handler can refer to the exception with name, Java exceptions are objects, so the statements in a catch clause can refer to the thrown exception object using the specified name.
printStackTrace:- It helps us to find the exact error location and name of the method causing the error in our code. In Java execution, each program has the details of its invoking methods onto the execution stack, plus the classes and object names and the line number of the code line that is being executing. Whenever an exception is triggered printStackTrace() can be used to print the contents of the execution stack, and we can fetch the details.
Division by Zero
We are dividing by zero and we are handling that exception using the catch block, in that block we are taking the output of “Stack” which is shown as ArthemeticException:/ by Zero and gives us the line where exception is thrown i.e 6 in our case.
1) We can have multiple Catch blocks, by providing one or more catch blocks directly after the try block.
2) We can Catch More Than One Type of Exception with only One Exception Handler(Catch). We need to specify the types of exceptions that block can handle, and separate each exception type with a vertical bar (|)
In this example, the catch parameter e is final(Constant value) and therefore we cannot assign any values to it within the catch block.
3) Arrange multiple, Catch blocks using narrow to broader approach.
Here incase of some I/O exception (say while working with files) , first block of catch will always be executed irrespective even “FileNotFoundException” is thrown.Beacuse “I/OException” is superclass to “FileNotfoundException” which is the subclass, so our correct order should be:-
4) Try-Catch block can also be followed by Finally Block(optional).
- This block of code always executes, whether or not an exception has occurred.
- Only in some exceptional scenarios it might not execute like the thread executing the try or catch code is interrupted or killed, JVM exits while the try or catch code is being executed.
- It is a good practice to use this block for code cleanup, to free the resources after the execution exits.
- The finally block is a key tool for preventing resource leaks. When closing a file or otherwise recovering resources, place the code in a finally block to ensure that resource is always recovered
5) Try block cannot exist without Catch or Final blocks and vice versa.
6) We can create our own exceptions and utilize the throws and throw keyword to initiate that exception.
7) “Exception” class can handle any type of exception, so our handler will look like
// Common exception handler
Note:-Always try to catch specific exceptions. Avoid catching System.Exception whenever possible.
8)Code that detects errors often does not know how to handle them.The best approach is to use exceptions.We catch them using Try-Catch and Exceptions are thrown using a throw statement.
But mostly it is recommend having exception handlers to be as specific as possible,firstly because a handler must do is determine what type of exception occurred before it can decide on the best recovery strategy, secondly this is general handler and can make code more error-prone by catching and handling exceptions that we never wanted to capture and for which the handler was not intended
What can be done when calling a function that may throw an exception?
1. Catch and handle the exception there itself
Method A calls Method B, and we are catching the exception in Method B itself.
|Catch Exception in the originating Method|
2. Catch the exception, then re-throw it or throw another exception
Method A calls Method B, and we are catching the exception in Method B and throwing another exception.
|Throw Exception to the calling Method|
3. Ignore the exception (let it "pass up" the call chain).
Method A calls Method B, and we are throwing the exception in Method B and it is catched by Main method
|Main method handles Exception|
Difference between Throw and Throws
Note:- We have taken the code example to explain the difference of Throws and Throw from the above complete code(Point 2)
|Throw v/s Throws in Java|
Why to use Exceptions?
It helps in error handling 🙂 , very simple and straightforward, but it also help us to give structure to our code by separating the “Error-Handed” code from the “Regular code”.
We can group same error types.
IOException exception represents any type of error that can occur when performing I/O.On the other hand “FileNotFoundException ” is the subclass of this, which handles only missing file exception.So we can have specific handlers that can handle a very specific exception
Or to catch all exception based on its group or general type by specifying any of the exception’s superclasses in the catch statement like I/O Exceptions