Is it possible to make a mistake that triggers others?

Asked

Viewed 91 times

5

Follow 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");
        }
    }
}

Exit:

Error 2

It is possible to make as soon as the error occurs in func2 he printe Error 2 and triggers this error for the func1 printing Error 1 as in the output example below?

Error 2
Error 1

  • 2

    A doubt, this is just curiosity or do you intend to implement it somewhere?

  • 1

    I ask because I see it as a bad practice, the exception is to be used when something unexpected happens. The best is always to try to treat all mistakes, rather than pillage exception upon other.

  • 2
  • I am studying DB, my class has several functions and all of them have error handling, however in some cases one function calls the other and if the last function gives error there will be problems in some objects at the end

  • 1

    Even so, this form will complicate you in the future, depending on the complexity. Take a look at the question that Linkei, the post is very enlightening, worthwhile :)

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
        }
    }
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

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

See if you really have to capture the exception and launch it again. Rarely is this necessary. What I see is that you do it by mistake. There is a case that needs to treat the exception in more than one step, but it is not so common. In most cases it is, or treats everything, or leaves for another place to treat.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.