[java knowledge point exception] the difference between throw new RuntimeException(e) and e.printStackTrace( )

Reprinted from: https://blog.csdn.net/xuzhuaaron1/article/details/73611404
e.printStackTrace( ) prints the exception stack information, while throw new RuntimeException(e) wraps the exception in a runtime exception and throws it. 

We often see this kind of writing
try{
....

}catch(Exception e){
e.printStackTrace( );
throw new RuntimeException(e);
//throw new RuntimeException(e.getMessage());



}
This is the general practice for handling exceptions that cannot be handled further. An exception occurred in the try block, it was caught, we first need to print the exception on the standard output but if there is no throw, the error is silently eaten by the catch block, and the program will continue to run. But at this time, it is very likely that the state of your program is wrong, and it is meaningless to continue, so you should continue to throw this exception. Of course you can write throw e;, but this e is a general exception, if it is thrown like this, you have to declare it with throws in the function header, for example:
public void abc() throws Exception
and then the function that calls this function is also We have to do this, so the general treatment is to wrap e as a runtime exception: new RuntimeException(e), so that there is no need to declare it in the function header.

However, this is only a general method of handling, and in actual programs, it is not necessary to rigorously disregard the actual situation and needs.
 
 
e.printStackTrace();在实际开发时意义不大,因为部署以后不会有人看控制台,这句很多情况下会被记录日志的代码代替。 throw new RuntimeException就是要把异常继续抛出,要么由上层方法解决,要么会终止程序运行,比如这里,如果初始化都无法正确完成,再继续运行下去也没有必要了。至于说多打印一句话,还是因为在工具环境下,你比较关注控制台,实际部署环境,没人看控制台信息,都会去看日志中记录的异常信息。 有结束进程的作用。
try catch如果不写throw new RuntimeException 只是不执行本方法后面的代码,然后跳出本方法后继续执行其他方法,不会结束程序 如果在其他应用中,还可以把异常抛给上层调用者来处理

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326548163&siteId=291194637