Throwing exceptions in Java

后端 未结 11 998
萌比男神i
萌比男神i 2020-12-30 16:23

I have a question about throwing exceptions in Java, a kind of misunderstanding from my side, as it seems, which I would like to clarify for myself.

I have been read

11条回答
  •  南笙
    南笙 (楼主)
    2020-12-30 16:49

    Exceptions should be thrown from a method when that method is incapable of resolving the exception on its own.

    For example, a FileNotFoundException is thrown from new FileInputStream(new File(filename)) because the FileInputStream itself can't handle a case where a file is missing; that exception needs to get thrown so the end-user application can handle the problem.

    There are some cases where exceptions could be handled within a method. For example, a Document model method throwing a BadLocationException could be handled within a sufficiently intelligent method. Depending on the problem, either the exception can be handled or re-thrown.

    (Anyway, I'd argue that throwing an exception from within a try-catch block so the catch block can be executed represents really bad logic flow)

提交回复
热议问题