简体   繁体   English

如何限制功能,使其不会引发任何异常

[英]How to restrict a function so that it can't throw any kind of exception

如何限制一个函数,使其不能抛出任何异常?

Catch all exception in the method. 捕获方法中的所有异常。

public void myMethod() {
    try {
       // do something
    } catch (Exception e) {
       e.printStackTrace();
    }
}

if you want to catch any kind of Exception or Error including OutOfMemoryError or ThreadDeath etc use 如果您想捕获任何异常或错误,包括OutOfMemoryError或ThreadDeath等,请使用

    } catch (Throwable t) {

Just wrap all of your code in a try catch block. 只需将所有代码包装在try catch块中。

public void someMethod(){
 try{
  //your code
 }catch (Exception e){
   //do nothing
 }
}

Read More about exceptions and Try/Catch on the Java Tutorials: http://docs.oracle.com/javase/tutorial/essential/exceptions/index.html 在Java教程上阅读有关异常和Try / Catch的更多信息: http : //docs.oracle.com/javase/tutorial/essential/exceptions/index.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM