Dif*_*ffy 11 java android exception-handling exception
我已经阅读了数百篇有关此事的帖子,但我仍然不清楚这一点.
当我写这样的函数
public List<String> getTrackIds(int limit) throws NotConnectedException, UnauthorizedException {
...
}
Run Code Online (Sandbox Code Playgroud)这意味着该函数可以抛出这些异常.但是不是需要在try/catch块中捕获它吗?在这种情况下,我将如何捕获异常?
throws
在调用函数中写一个子句.再次,如果我不编写try/catch块,我将如何捕获这些异常?使用例外,您可以:
try catch
块来处理它们.(这是我的问题)throws
在方法规范中声明它们.(这不是我的问题,你处理它)对于后一种可能性,该方法的调用者再次具有相同的两个选项.正如您所看到的,Exceptions
可以将其声明为throws
程序流程的所有方式.甚至static void main(String[] args)
可以使用这些throws
子句声明,这最终意味着当Exception
抛出其中一个声明时,您的应用程序将崩溃.
我们来看下面的例子:
/**
* Throws a MyException.
*/
public static void methodThrowsException() throws MyException {
throw new MyException();
}
/**
* Calls methodThrowsException(), and handles the thrown MyException
*/
public static void myMethod() {
try {
methodThrowsException();
} catch(MyException e) {
/* Do something */
}
}
/**
* Calls methodThrowsException, but does not handle the thrown MyException.
*/
public static void mySecondMethod() throws MyException {
methodThrowsException();
}
Run Code Online (Sandbox Code Playgroud)
调用myMethod
或时mySecondMethod
,会发生以下情况:
public static void main(String[] args) {
myMethod(); /* No catching needed */
try {
mySecondMethod();
} catch(MyException e){
/* Catching needed */
}
}
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,mySecondMethod
刚刚将捕获问题转移MyException
给了调用者.
归档时间: |
|
查看次数: |
5586 次 |
最近记录: |