Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
284 views
in Technique[技术] by (71.8m points)

java - 了解Java中的检查与未检查异常(Understanding checked vs unchecked exceptions in Java)

Joshua Bloch in " Effective Java " said that

(约书亚·布洛赫(Joshua Bloch)在《 有效的Java 》中说)

Use checked exceptions for recoverable conditions and runtime exceptions for programming errors (Item 58 in 2nd edition)

(将检查的异常用于可恢复的条件,将运行时异常用于编程错误(第二版中的项目58))

Let's see if I understand this correctly.

(让我们看看我是否正确理解了这一点。)

Here is my understanding of a checked exception:

(这是我对检查异常的理解:)

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
}

1. Is the above considered a checked exception?

(1.以上是否被视为经过检查的异常?)

2. Is RuntimeException an unchecked exception?

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

Here is my understanding of an unchecked exception:

(这是我对未经检查的异常的理解:)

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);?
}

4. Now, couldn't the above code also be a checked exception?

(4.现在,上面的代码难道不是一个检查异常吗?)

I can try to recover the situation like this?

(我可以尝试恢复这种情况吗?)

Can I?

(我可以吗?)

(Note: my 3rd question is inside the catch above)

((注:我的第三个问题是,里面catch上))

try{
    String filePath = //read in from user input file path
    File file = new File(filePath);
    FileInputStream fis = new FileInputStream(file);   
}catch(FileNotFoundException e){
    //Kindly prompt the user an error message
    //Somehow ask the user to re-enter the file path.
}

5. Why do people do this?

(5.人们为什么这样做?)

public void someMethod throws Exception{

}

Why do they let the exception bubble up?

(为什么他们让异常冒出来?)

Isn't handling the error sooner better?

(处理错误不是更好吗?)

Why bubble up?

(为什么冒泡?)

6. Should I bubble up the exact exception or mask it using Exception?

(6.我应该冒充确切的异常还是使用Exception屏蔽它?)

Below are my readings

(以下是我的读物)

In Java, when should I create a checked exception, and when should it be a runtime exception?

(在Java中,什么时候应该创建一个检查异常,什么时候应该是运行时异常?)

When to choose checked and unchecked exceptions

(何时选择已检查和未检查的异常)

  ask by Thang Pham translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Many people say that checked exceptions (ie these that you should explicitly catch or rethrow) should not be used at all.

(许多人说,根本不应该使用检查异常(即应明确捕获或重新抛出的异常)。)

They were eliminated in C# for example, and most languages don't have them.

(例如,它们在C#中已被淘汰,并且大多数语言都没有它们。)

So you can always throw a subclass of RuntimeException (unchecked exception)

(因此,您始终可以抛出RuntimeException的子类(未经检查的异常))

However, I think checked exceptions are useful - they are used when you want to force the user of your API to think how to handle the exceptional situation (if it is recoverable).

(但是,我认为检查异常非常有用-当您要强制API用户考虑如何处理特殊情况(如果可恢复)时,可以使用它们。)

It's just that checked exceptions are overused in the Java platform, which makes people hate them.

(只是在Java平台中过度使用了检查异常,这使人们讨厌它们。)

Here's my extended view on the topic .

(这是我对该主题的扩展看法 。)

As for the particular questions:

(至于特定的问题:)

  1. Is the NumberFormatException consider a checked exception?

    (NumberFormatException是否考虑检查异常?)
    No. NumberFormatException is unchecked (= is subclass of RuntimeException ).

    (否NumberFormatException未选中(=是RuntimeException子类)。)

    Why?

    (为什么?)

    I don't know.

    (我不知道。)

    (but there should have been a method isValidInteger(..) )

    ((但应该有一个方法isValidInteger(..) ))

  2. Is RuntimeException an unchecked exception?

    (RuntimeException是未经检查的异常吗?)
    Yes, exactly.

    (对,就是这样。)

  3. What should I do here?

    (我该怎么办?)
    It depends on where this code is and what you want to happen.

    (这取决于该代码在哪里以及您想要发生什么。)

    If it is in the UI layer - catch it and show a warning;

    (如果它在UI层中-捕获并显示警告;)

    if it's in the service layer - don't catch it at all - let it bubble.

    (如果它在服务层中-根本不要抓住它-让它冒泡。)

    Just don't swallow the exception.

    (只是不要吞下异常。)

    If an exception occurs in most of the cases you should choose one of these:

    (如果在大多数情况下发生异常,则应选择以下一种:)

    • log it and return

      (记录并返回)

    • rethrow it (declare it to be thrown by the method)

      (重新抛出它(声明它被方法抛出))

    • construct a new exception by passing the current one in constructor

      (通过在构造函数中传递当前异常来构造新异常)

  4. Now, couldn't the above code also be a checked exception?

    (现在,上面的代码难道不是一个检查异常吗?)

    I can try to recover the situation like this?

    (我可以尝试恢复这种情况吗?)

    Can I?

    (我可以吗?)
    It could've been.

    (可能是这样。)

    But nothing stops you from catching the unchecked exception as well

    (但是也没有什么可以阻止您捕获未经检查的异常)

  5. Why do people add class Exception in the throws clause?

    (人们为什么在throws子句中添加类Exception)
    Most often because people are lazy to consider what to catch and what to rethrow.

    (大多数情况下,是因为人们懒于考虑要捕获什么和重新抛出什么。)

    Throwing Exception is a bad practice and should be avoided.

    (抛出Exception是一种不好的做法,应该避免。)

Alas, there is no single rule to let you determine when to catch, when to rethrow, when to use checked and when to use unchecked exceptions.

(las,没有一个单一的规则可以让您确定何时捕获,何时重新抛出,何时使用已检查的异常以及何时使用未检查的异常。)

I agree this causes much confusion and a lot of bad code.

(我同意这会引起很多混乱和很多错误代码。)

The general principle is stated by Bloch (you quoted a part of it).

(Bloch陈述了一般原则(您引用了其中一部分)。)

And the general principle is to rethrow an exception to the layer where you can handle it.

(通常的原则是将异常抛出到可以处理它的层。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...