About Java Exception Handling

Asked 2 years ago, Updated 2 years ago, 30 views

I don't know exactly what to use between "try-catch" and "throws" exceptions.
In what situations do you use try-catch to handle exceptions, and do you use "throws"?

java

2022-09-30 17:38

2 Answers

It's an old article.
"Whether or not to use arrows depends on the role of the method"
http://www.atmarkit.co.jp/ait/articles/0611/22/news144.html


2022-09-30 17:38

I think it depends on the specifications of the software to be developed.
When an exception occurs,

  • Show users an error message and prompt them to take action (for example, review the wrong file location)
  • Run alternative actions internally to continue processing (for example, create a new file because there is no file)

If you intend to そのdo something about that exception が as shown in , capture it individually with try-catch and incorporate error indications, alternative actions, etc.
At this point, it's ants who browse and propagate to the layer where error indication and alternative actions should be implemented, but in some cases, it's also good to define the appropriate exception class for that layer, wrap it, and then browse again (using arrows).

Otherwise, if you don't expect (do not support) the use of such an exception in the first place, catch it with try-catch, wrap it up with RuntimeException and so on, and then browse again (do not use arrows).

This "unexpected error" will be aggregated somewhere in the software.Try-catch is fine, and if you're using a framework, you'll have some kind of exception aggregation mechanism.
I think the only thing you can do about "unexpected errors" is to safely stop the software processing and spout debug logs.
Finally, it would be good to show the user something like, "Something strange has happened, so please contact the developer."


2022-09-30 17:38

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.