Sam*_*ell 2 java exception throw checked-exceptions
我是Java的初学者.
我声明了一个方法public void method() throws Exception,但每当我尝试通过使用在同一个类的另一个区域中调用该方法时method();,我得到一个错误:
Error: unreported exception java.lang.Exception; must be caught or declared to be thrown
Run Code Online (Sandbox Code Playgroud)
如何在不收到此错误的情况下使用该方法?
在另一个调用方法中method(),您将不得不以某种方式处理method()抛出的异常.在某些时候,它需要被捕获,或者一直声明到main()启动整个程序的方法.所以,要么抓住异常:
try {
method();
} catch (Exception e) {
// Do what you want to do whenever method() fails
}
Run Code Online (Sandbox Code Playgroud)
或用你的其他方法声明:
public void otherMethod() throws Exception {
method();
}
Run Code Online (Sandbox Code Playgroud)