我本周五正在攻读CS考试,并且在这里遇到了一个障碍.问题要求我处理异常,然后使用两种不同的方法传播异常,但我的印象是它们是同一个东西.有人可以帮忙吗?练习题列在下面.
您将获得以下课程:
public class ReadData {
public void getInput() {
getString();
getInt();
}
public void getString() throws StringInputException {
throw new StringInputException();
}
public void getInt() throws IntInputException {
throw new IntInputException();
}
}
class StringInputException extends Exception {}
class IntInputException extends Exception {}
Run Code Online (Sandbox Code Playgroud)
上面的代码将导致getInput()方法中的编译错误.使用两种不同的技术重写getInput()方法:
Method 1 - Handle the exception
Method 2 - Propagate the exception
Run Code Online (Sandbox Code Playgroud)
以便代码编译.
它们不是同一件事.传播基本上意味着重新抛出异常,即允许在代码中的某个地方处理它; 通常,如果在当前级别无法对异常进行任何操作,则会执行此操作.处理异常意味着捕获它并实际执行某些操作 - 通知用户,重试,记录 - 但不允许异常更进一步.