Question

In my efforts to learn and better understand Java, I have been told that it is generally a bad practice to keep my code nested like it is below. My question is how can I make it so that it performs the same functions while making it a little easier to read. Thanks!

class Test {
    public static void main(String[] args) {
        try {
            int zero = 0;
            int y = 2/zero;
            try {
                Object s = null;
                System.out.println(s.toString());
            }
            catch(NullPointerException e) {
                System.out.println(e);
            }
        }
        catch(ArithmeticException e) {
            System.out.println(e);
        }
    }
}
Was it helpful?

Solution

You can remove one try by writing it like this for example.

try {
    int zero = 0;
    int y = 2/zero;

    Object s = null;
    System.out.println(s.toString());
} catch(NullPointerException e) {
    System.out.println(e);
} catch(ArithmeticException e) {
    System.out.println(e);
}

This is certainly more readable, but it is not neccesarily better. That depends on your use case.

You could not do this

try {
    int zero = 0;
    int y = 2/zero;

    Object s = null;
    try {            
        System.out.println(s.toString());
    } catch(NullPointerException e) {
        System.out.println("'s' was null, creating a new 's'");
        s = new Object();
    }
    System.out.println(s.toString());

} catch(ArithmeticException e) {
    System.out.println(e);
}

OTHER TIPS

It all depends on where you want to catch the error. If you want to catch 2 different kinds of exceptions in 1 catch block, use the | operator.

try {

}catch(NullPointerException | ArithmeticException e) {

}

If you want 2 different catch blocks, just add another one

try {

}catch(NullPointerException npe) {

}catch(ArithmeticException ae) {

}

You must surround with try/catch for methods/instances that throw an exception, or if you choose to throw a new exception. But it all depends on where you want to catch the error. When an exception is thrown, all code within the try block that comes AFTER where the exception was thrown will be skipped, and the catch block connected to that try block will trigger

You could add multiple catch statements at the end of a single try statement such as

catch(NullPointerException e) {
            System.out.println(e);
        }

catch(ArithmeticException e) {
        System.out.println(e);
       }

Instead of having a try/catch within another try/catch

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top