Java structure. Is there a need to insert try statements?

I only thought about it as possible, but I want to know if this is considered "bad practice." I believe that this is so, but I want to ask him to look at him to check my opinion.

Is it bad to do something like this:

try{ something(); somethingelse(); try{ foo(); bar(); }catch(Exception e){ e.printStackTrace(); } somethingelseagain(); }catch(Exception e){ e.printStackTrace(); } 

I think it should never be necessary to do this, since anything that raises an exception will in any case cause the first catch.

Submissions are welcome.

+4
source share
3 answers

In your example, as written, the internal catch is a bit redundant.

However, nested catches will be more applicable in circumstances such as:

  • catch various exceptions

  • does something else in a handler block for two catches

  • an internal catch can catch an exception, do something, and then rethrow the same exception that could catch a catch catch block

Also, don't forget about the potential use of the finally block, which can execute cleanup code even if an exception is detected.

Typically, you are trying to catch the most explicitly printed (i.e. specific) exceptions (exceptions).

The topic of exceptions is interesting, and not without controversy .

+4
source

The case, which, I think, you might want to embed in a try statement, is if you request user input in your catch and this input may be invalid.

+1
source

A nested try-catch fully justified when circumstances require it. For example, you do not want to skip any steps and exit the main try if any method throws a specific exception. If it raises any other exception, then you want normal behavior.

0
source

Source: https://habr.com/ru/post/1447826/


All Articles