How to Catch Exceptions in Java? – User friendly Tech help

We understood the basics of Exception in Java, now we will move towards handling these exceptions. We are aware of the fact that when error is detected, an exception is thrown. This means the normal code execution stops and the control are transferred to the catch clause for that exception of the first enclosing try block. The try block might be in the current function (the one that caused the error), or it might be in some function that called the current function (if the current function is not prepared to handle the exception, it is “passed up” the call chain).Furthermore in case no currently active function is prepared to catch the exception, an error message is printed and the execution stops.
n
nLets elaborate on what we said above.We can connect on FB for more learning!!

n

How to catch exceptions?
n

n

n

n

n

n

n

n

n

Try-Catch

n

nUsing Try-Catch:-
n
nTry 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.
n
nCatch 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)
n
nSyntax:-

n

try {

n

//Our code 
} catch (ExceptionType name) {
name.printStackTrace();
}

n


n


n

Explanation:-

n

ExceptionType:- declares the type of exception that the handler can handle.

n


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.
n
nprintStackTrace:- 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.
n
nCode:-
n
nDivision by Zero 

n

public class ExceptionHandling {
public static void main(String[] args) {
try {
int a = 1/0;
} catch (Exception e) {
// TODO Auto-generated catch block e.printStackTrace();
System.out.println("We are in the catch block"); } }}

n

nOutput:-
n

n

n

n

n

n

n

n

n

Arithmetic Exception

n

Explanation:-
n
nWe 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.
n
n
nImportant Tips:- 
n
n1) We can have multiple Catch blocks, by providing one or more catch blocks directly after the try block.
n
nSyntax:-

n

try {

n

} catch (ExceptionType1 name1) {
} catch (ExceptionType2 name2) {}

n

n2) 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 (|)
n
nSyntax:-

n

try {

n

} catch (IndexOutOfBoundsException | IOException e){} 

n

nIn this example, the catch parameter e is final(Constant value) and therefore we cannot assign any values to it within the catch block.
n
n3) Arrange multiple, Catch blocks using narrow to broader approach.
n
For example:- 

n

catch (I/OException e) {

n

 //statements to handle this exception 

n

}
catch (FileNotFoundExcetption e) {
//statements to handle this exception }

n

nHere 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:-

n

catch (FileNotFoundExcetption e) {
//statements to handle this exception }
catch (I/OException e) {
//statements to handle this exception }

n

4) Try-Catch block can also be followed by Finally Block(optional).

n

    n

  • This block of code always executes, whether or not an exception has occurred.
  • n

  •  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.
  • n

  • It is a good practice to use this block for code cleanup, to free the resources after the execution exits. 
  • n

  • 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
  • n

n

Syntax:-
n

n

try{
//Our code}
catch(ExceptionType name){ }
finally{
//I will always executes.}

n

5) Try block cannot exist without Catch or Final blocks and vice versa.
n
n6) We can create our own exceptions and utilize the throws and throw keyword to initiate that exception.

n

7) “Exception” class can handle any type of exception, so our handler will look like
n
nSyntax:-
n// Common exception handler

n

catch (Exception e) {    ...}

n

nNote:-Always try to catch specific exceptions. Avoid catching System.Exception whenever possible.
n
n8)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.
n
nBut 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
n
nWhat can be done when calling a function that may throw an exception?
n
n1. Catch and handle the exception there itself
n
Example :- 
nMethod A calls Method B, and we are catching the exception in Method B itself.
n

n

public class ExceptionHandling {
public static void main(String[] args){
//Calling MethodA MethodA(); }
//MethodA
static void MethodA(){
//Call to MethodB MethodB();
System.out.println("We are inside MethodA"); }
//MethodB
static void MethodB(){
try {
int a = 1/0;
} catch (Exception e) {
// TODO Auto-generated catch block e.printStackTrace();
System.out.println("We are in the catch block of MethodB"); } }}

n

nOutput:-

n

n

n

n

n

n

n

n

Catch Exception in the originating Method

n

n2. Catch the exception, then re-throw it or throw another exception
n
Example :- 
nMethod A calls Method B, and we are catching the exception in Method B  and throwing another exception.
n

n

public class ExceptionHandlingThrow {
public static void main(String[] args){
//Calling MethodA MethodA(); }
//MethodA
static void MethodA(){
//Handling the thrown Exception
try{
//Call to MethodB MethodB();
}catch(ArithmeticException e){
System.out.println("We are inside MethodA it will catch Exception"); System.out.println(e.getMessage()); } }
//MethodB
static void MethodB() throws ArithmeticException{
try {
int a = 1/0;
} catch (Exception e) {
// TODO Auto-generated catch block
System.out.println("We are in the catch block of MethodB and it will Throw Exception");
throw new ArithmeticException("Exception of Divide by Zero"); } }}

n


n

nOutput:-

n
n
n
n

n

n

n

n

n

n

n

Throw Exception to the calling Method

n
n

3. Ignore the exception (let it "pass up" the call chain).

n

Example :- 

n

Method A calls Method B, and we are throwing the exception in Method B and it is catched by Main method
n

n

public class ExceptionHandlinginMainMethod {
public static void main(String[] args){
//Calling MethodA
try{ MethodA();
}catch(Exception e){
System.out.println("We are inside Main Function"); e.printStackTrace(); } }
//MethodA
static void MethodA(){
//Call to MethodB MethodB(); }
//MethodB
static void MethodB() {
System.out.println("We are inside MethodB it will not catch Exception");
int a = 1/0; } }

n

nOutput:-
n

n

n

n

n

n

n

n

n

Main method handles Exception

n

nDifference between Throw and Throws
n
nNote:- We have taken the code example to explain the difference of Throws and Throw from the above complete code(Point 2)
n

n

n

n

n

n

n

n

n

Throw v/s Throws in Java

n

n
nWhy to use Exceptions?
n
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”.
n
nWe can group same error types.
n
nFor example:-
nIOException 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

n

catch (FileNotFoundException e) {    ...}

n

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

n

catch (IOException e) {    ...}
Was this article helpful?
YesNo

Similar Posts