抛出异常处理中的子句

Dif*_*ffy 11 java android exception-handling exception

我已经阅读了数百篇有关此事的帖子,但我仍然不清楚这一点.

这意味着该函数可以抛出这些异常.但是不是需要在try/catch块中捕获它吗?在这种情况下,我将如何捕获异常?

  • .当我尝试调用这个函数时,它必须写入try/catch块throws在调用函数中写一个子句.再次,如果我不编写try/catch块,我将如何捕获这些异常?

nha*_*man 9

使用例外,您可以:

  • 使用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给了调用者.