相关疑难解决方法(0)

Java:已检查vs未经检查的异常说明

我已经在StackOverFlow上阅读了有关已检查和未经检查的异常的多个帖子.老实说,我还是不太确定如何正确使用它们.

Joshua Bloch在" Effective Java "中说过

对可恢复条件使用已检查的异常,对编程错误使用运行时异常(第2版中的第58项)

让我们看看我是否正确理解这一点.

以下是我对已检查异常的理解:

try{
    String userInput = //read in user input
    Long id = Long.parseLong(userInput);
}catch(NumberFormatException e){
    id = 0; //recover the situation by setting the id to 0
}
Run Code Online (Sandbox Code Playgroud)

1.以上是否考虑了检查异常?

2. RuntimeException是未经检查的异常吗?

以下是我对未经检查的异常的理解:

try{
    File file = new File("my/file/path");
    FileInputStream fis = new FileInputStream(file);   
}catch(FileNotFoundException e){

//3. What should I do here?
    //Should I "throw new FileNotFoundException("File not found");"?
    //Should I log?
    //Or should I System.exit(0);?
}
Run Code Online (Sandbox Code Playgroud)

4.现在,上述代码也不能成为检查异常吗?我可以尝试恢复这样的情况吗?我可以吗?(注意:我的第3个问题在catch上面)

try{
    String …
Run Code Online (Sandbox Code Playgroud)

java exception runtimeexception checked-exceptions unchecked-exception

678
推荐指数
11
解决办法
31万
查看次数

我应该在C++中使用异常说明符吗?

在C++中,您可以通过使用异常说明符指定函数可能会也可能不会抛出异常.例如:

void foo() throw(); // guaranteed not to throw an exception
void bar() throw(int); // may throw an exception of type int
void baz() throw(...); // may throw an exception of some unspecified type
Run Code Online (Sandbox Code Playgroud)

由于以下因素,我对实际使用它们表示怀疑:

  1. 编译器并没有以任何严格的方式真正强制执行异常说明符,因此效益并不高.理想情况下,您希望得到编译错误.
  2. 如果函数违反了异常说明符,我认为标准行为是终止程序.
  3. 在VS.Net中,它将throw(X)视为throw(...),因此遵守标准并不强.

你认为应该使用异常说明符吗?
请回答"是"或"否"并提供一些理由来证明您的答案.

c++ exception function throw specifier

119
推荐指数
5
解决办法
3万
查看次数