Java – handling catastrophic exceptions

I read in the c# primer that if you don't know how to handle it, you shouldn't find exceptions Considering these suggestions when programming in Java, I sometimes find that I don't know how to handle exceptions, but I have to grasp it or "infiltrate it" to avoid compilation errors I prefer not to use the throw clause to confuse the method throughout the call tree, so I often use "convert" exceptions to runtimeexceptions, as shown below Adding the throws clause to many methods seems lengthy and distracting for exceptions that are not really "handled" (handled correctly) Is the following bad style, if so, what better way to deal with this?

try {
  thread.join();
}
catch (InterruptedException e) {
      Console.printwriter.format("%s\n",e.printStackTrace());
  throw new RuntimeException();
}

Editor: in addition to clutter, there is another problem with penetrating exceptions: after code modification, you may eventually get some unnecessary throw clauses The only way I know to clear them is through trial and error: delete them and see if the compiler complains Obviously, this is annoying if you want to keep your code clean

Solution

The Java partition between checked and unchecked exceptions is somewhat contrary

If you control the interface, it is usually best to add a throws clause to the signature

If you are in a situation where you cannot handle an exception but do not allow it to bubble because the exception signature is checked, it is common practice to wrap the exception into an exception that can be thrown again (usually runtimeException)

In many cases, you may want to use another checked exception, such as IOException or sqlexception But this is not always an option

However, in your example, include the original exception as "cause":

throw new RuntimeException(e);

This also eliminates the need for logging (because it can also be deferred to someone who can handle exceptions, and all the information still exists)

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>