Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to catch Exceptions occured in Catch block in Java

I need to handle Exceptions which are raised by Catch block code in Java

like image 733
Chandra Shekhar Avatar asked Oct 29 '25 07:10

Chandra Shekhar


2 Answers

Example, to "handle" an Exception:

try 
{
 // try do something
} 
catch (Exception e) 
{
    System.out.println("Caught Exception: " + e.getMessage());
    //Do some more
}

More info see: See: https://docs.oracle.com/javase/tutorial/essential/exceptions/catch.html

However if you want another catch in your try catch, you can do the following:

 try 
     {
           //Do something
     } 
     catch (IOException e) 
     {
            System.out.println("Caught IOException: " + e.getMessage());

            try
            {
                 // Try something else
            }
            catch ( Exception e1 )
            {
                System.out.println("Caught Another exception: " + e1.getMessage());                     
            }
     } 

Be careful with nested try/catch, when your try catch is getting to complex/large, consider splitting it up into its own method. For example:

try {
    // do something here
}
catch(IOException e)
{
    System.out.println("Caught IOException: " + e.getMessage());
    foo();
}

private void foo()
{
    try {
        // do something here (when we have the IO exception)
    }
    catch(Exception e)
    {
        System.out.println("Caught another exception: " + e.getMessage());
    }
}
like image 183
M. Suurland Avatar answered Oct 31 '25 00:10

M. Suurland


Instead of cascading try/catch (like in most of the other answers), I advise you to call another method, executing the required operations. Your code will be easier to maintain by this way.
In this method, put a try/catch block to protect the code.

Example :

public int classicMethodInCaseOfException(int exampleParam) {
    try {
        // TODO
    }
    catch(Exception e)
    {
        methodInCaseOfException();
    }
}


public int methodInCaseOfException()
{
    try {
        // TODO
    }
    catch(Exception e)
    {
        //TODO
    }
}
like image 43
Spilarix Avatar answered Oct 31 '25 00:10

Spilarix



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!