Would you ever NOT catch an exception, or throw an exception that won't be caught?

前端 未结 14 961
感情败类
感情败类 2021-01-03 09:49

I\'ve dealt with instances where I would throw/rethrow an exception knowing that the code surrounding it would catch the specific exception. But is there any time you would

14条回答
  •  没有蜡笔的小新
    2021-01-03 09:56

    It depends on the type of application. Web applications can continue running even after exceptions have bubbled up to the execution context.

    It is common practice to 'throw/rethrow' an exception if you catch the exception at a level where it can't be dealt with. But, you would almost always add context to the issue, at the very least add some logging at the higher level to say that it was caught and rethrown.

    for example

    A calls B calls C (throws exception)

    B catches/rethrows

    A catches.

    In this case, you would want B to add some logging so that you can differentiate between B generating and throwing an error, and C generating and throwing an error. That would allow you a greater ability to debug and fix problems later.

    In general you will almost NEVER want an exception to kill your program. The best practice is to catch the except and exit gracefully. This allows you to save any currently open information and release resources that are being used so they don't become corrupted. If you intend to exit, you can create your own 'core-dump' information report that includes the things you were doing when you caught the fatal exception.

    If you let the exception kill your process you are eliminating your chance to get custom tailored crash information, and you are also skipping the part where you provide the user with a friendly error message and then exit.

    So, I would recommend ALWAYS catching exceptions, and never voluntarily letting them run amok in your program.

    EDIT

    If you are writing a library, you have to choose ahead of time whether your function will throw an exception, or be exception safe. In those cases, sometimes you will throw an exception and have no idea if the calling party will catch it. But in that case, catching it is not your responsibility, as long as the api declares that the function could throw exceptions. (I'm looking for a word that means 'could possibly throw exception'... anyone know what it is? It's going to bug me all day.)

提交回复
热议问题