Is it possible to handle exceptions without catch?

Asked

Viewed 50 times

1

I’m learning about treating exceptions and I’ve come to wonder if there’s any possibility of using the treatment without the command catch.

  • 4

    Hello Lucas. Your question is a little wide / ambiguous. In Java it is possible to have a sequence try {} finally {} without catch (e.g., to execute a given command after try even if an exception occurs midway). The block catch however, it is the mechanism made available by language to treat / react to exceptions. There are also alternative error handling mechanisms such as error code return and monadic constructs (e. g., Try, Either, CompletableFuture). If you clarify better what you mean by "using the treatment" this may facilitate an answer.

1 answer

1


Hello,

I don’t think so.

The idea behind the exceptions is that when you use the Try keyword, you are telling the language to make a copy of the current thread’s runstack. There are the variables of the current function and the functions that called it. And these variables point to the objects in the heap.

When the exception occurs, your stack is in a different state. The copy made by the immediately preceding Try will replace the current one, making the application "go back" to a previous state that is safe (or should be).

If no catch exists until the main method. JDK itself will treat the exception and exit the application prematurely.

To java 8 specification says something similar (translation done by me freely):

The keyword throw starts an exception to be launched. The result is the transfer of the execution control that will leave multiple blocks ({}), (class) builders, inicalizers, initializers and metic calls until a Try block is found treating (catches) the generated exception. If no Try is found, then thread execution will be finished...

Browser other questions tagged

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