Is it possible to throw an error that triggers others?

4

Here's an example:

public class Teste
{
    public static void main(String[] args)
    {
        func1();
    }

    public static void func1()
    {
        try
        {
            func2();
        }
        catch (Exception e)
        {
            System.err.println("Error 1\n");
        }
    }

    public static void func2()
    {
        try
        {
            int x = 1 / 0;
        }
        catch (Exception e)
        {
            System.err.println("Error 2\n");
        }
    }
}

Output:

  

Error 2

Is it possible to cause that as soon as the error occurs in func2 it printe Error 2 and trigger that error to func1 printing Error 1 as in the output example below?

  

Error 2
Error 1

    
asked by anonymous 21.10.2016 / 21:46

1 answer

4

Yes, it is possible, just relaunch the exception:

class Teste {
    public static void main(String[] args) {
        func1();
    }

    public static void func1() {
        try {
            func2();
        } catch (Exception e) {
            System.out.println("Error 1");
         }
    }

    public static void func2() {
        try {
            int x = 1 / 0;
        } catch (Exception e) {
            System.out.println("Error 2");
            throw e; // <==================== relançou aqui
       }
    }
}

See running on ideone and on CodingGround .

I just hope you're capturing Exception as a quick test . I like to answer these questions about exceptions, but I always fear using them. Most programmers abuse them.

See if you really have to catch the exception and throw it again. Rarely is this necessary. What I see most is to do this by mistake. You have to handle the exception in more than one step, but it is not so common. In most cases it is, or treats everything, or leaves it to another location to treat.

    
21.10.2016 / 22:06