Java 传播和处理之间有什么区别?
我正在准备本周五的CS考试,在这里遇到了一个麻烦。这个问题要求我处理异常,然后使用两种不同的方法传播异常,但我觉得它们是一样的。有人能帮忙吗?练习题列在下面 您将获得以下课程:Java 传播和处理之间有什么区别?,java,exception,Java,Exception,我正在准备本周五的CS考试,在这里遇到了一个麻烦。这个问题要求我处理异常,然后使用两种不同的方法传播异常,但我觉得它们是一样的。有人能帮忙吗?练习题列在下面 您将获得以下课程: public class ReadData { public void getInput() { getString(); getInt(); } public void getString() throws StringInputException { throw ne
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 {}
上面的代码将导致getInput()方法中的编译错误。
使用两种不同的技术重写getInput()方法:
Method 1 - Handle the exception
Method 2 - Propagate the exception
这样代码就可以编译了。它们不是一回事。传播基本上意味着重新抛出异常,也就是说,允许代码中更高的位置来处理它;通常,如果在当前级别无法对异常执行任何操作,则会执行此操作。处理异常意味着捕获异常并实际处理它——通知用户、重试、记录——但不允许异常进一步发展 “处理异常”意味着捕获异常并执行任何必要的操作以正常继续
“传播异常”意味着不捕获异常并让您的调用方处理它。dictionary.com是您的朋友。 有时我们不得不应付那种讨厌的英语 Handle意味着做一些例外的事情, 中止程序, 打印错误, 乱搞数据 传播它意味着将它转发到其他地方,即重新抛出它。
类示例{
class Example {
// a method that throws an exception
private void doSomething() throws Exception {
throw new Exception();
}
public void testHandling() {
try {
doSomething();
} catch (Exception e) {
// you caught the exception and you're handling it:
System.out.println("A problem occurred."); // <- handling
// if you wouldn't want to handle it, you would throw it again
}
}
public void testPropagation1() throws Exception /* <- propagation */ {
doSomething();
// you're not catching the exception, you're ignoring it and giving it
// further down the chain to someone else who can handle it
}
public void testPropagation2() throws Exception /* <- propagation */ {
try {
doSomething();
} catch (Exception e) {
throw e; // <- propagation
// you are catching the exception, but you're not handling it,
// you're giving it further down the chain to someone else who can
// handle it
}
}
}
//引发异常的方法
私有void doSomething()引发异常{
抛出新异常();
}
公共void testHandling(){
试一试{
doSomething();
}捕获(例外e){
//您捕获了异常并正在处理它:
System.out.println(“出现问题”)//