Should I catch and wrap general Exception?

前端 未结 14 1057
一向
一向 2020-12-30 04:19

Can following code be considered as a good practice? If not, why?

try
{
    // code that can cause various exceptions.         


        
相关标签:
14条回答
  • 2020-12-30 04:59

    It might be good practice or might not depending on the scenario. Though I am not an expert here, to my knowledge I consider doing this is fine when you are not sure about exception. I see you are considering a code in try that can throw multiple exceptions. If you are not sure about which exception can be thrown, it is always better to do it the way you have done it. Anyway the execution will not allow you to execute multiple catch blocks. Whenever you hit first catch block, control will go to finally or wherever next you want it to go but definitely not another catch block.

    0 讨论(0)
  • 2020-12-30 05:00

    No, generally, you should not do that: this may mask the real exception, which may indicate programming issues in your code. For example, if the code inside the try / catch has a bad line that causes an array index out of bound error, your code would catch that, too, and throw a custom exception for it. The custom exception is now meaningless, because it reports a coding issue, so nobody catching it outside your code would be able to do anything meaningful with it.

    On the other hand, if the code inside the try / catch throws exceptions that you expect, catching and wrapping them in a custom exception is a good idea. For example, if your code reads from some special file private to your component, and the read causes an I/O exception, catching that exception and reporting a custom one is a good idea, because it helps you hide the file operation from the caller.

    0 讨论(0)
  • 2020-12-30 05:04

    After reading the question, answers and the comments posted, I think a thorough answer by Iain Galloway could explain much of it in broader way.

    My short and sweet point to explain it,

    1. The exceptions should be caught and custom exception should only be thrown when you want to hide the technical details from the end user and want only user to get informed that something failed with some proper message but on the other hand would always log the same exception to the log file so that we can provide some technical assistance and help to the user if the same scenario occurs frequently and from the log file we get the information that we need (technically).
    2. You explicitly catch some exception type and know the exact scenario in what case the exception is thrown by the method and then handle it and have some predefined codes that can explain the error in the other methods calling the function and have some actions to take on that error codes.
      This could rather help if you call many functions and they all throw some pre-defined exception with exception codes which can help categorizing them and take some actions accordingly.

    In some other comment you mentioned, what about system critical exceptions like OutOfMemoryException you would only be able to catch those exception if you have explicitly added, [HandleProcessCorruptedStateExceptions] section over the function and to get detail answer in what scenario you should handle it read this SO post

    0 讨论(0)
  • 2020-12-30 05:06

    Depends on what you have to do with when exception arises. If you wish to globally handle all the exceptions, that's OK to re-throw the exception to the caller method and let it handle the exceptions. But there are many scenarios where exceptions must be handled locally, in such cases, catching exception with known types should be preferred and a last catch should catch Exception ex (to catch an unexpected exception) and re-throw the exception to caller.

    try
    {
        // code that can cause various exceptions...
    }
    catch (ArithmeticException e)
    {
        //handle arithmetic exception
    }
    catch (IntegerOverflowException e)
    {
        //handle overflow exception
    }
    catch (CustomException e)
    {
        //handle your custom exception if thrown from try{} on meeting certain conditions.
    }
    catch (Exception e)
    {
        throw new Exception(e); //handle this in the caller method
    }
    
    0 讨论(0)
  • 2020-12-30 05:08

    You can use ellipses too.

       catch (...) 
       {
            // catches all exceptions, not already catches by a catch block before
            // can be used to catch exception of unknown or irrelevant type
       }
    

    Except this what you can do is nested try-catch

    try
    {
        //some code which is not for database related 
        try
        {
          //database related code with connection open
        }
        catch(//database related exception)
        {
            //statement to terminate
        }
        **finally()
        {
            //close connection,destroy object
        }**
    }
    catch(//general exception)
    {
        //statement to terminate
    }
    

    According to me, this would help you to get more concise idea of your error type.

    0 讨论(0)
  • 2020-12-30 05:11

    It's completely OK. You don't have to catch each exception type separately. You can catch specific type of exception, if you want to handle it in specific way. If you want to handle all exceptions in same way - catch base Exception and handle it as you do. Otherwise you will have duplicated code in each catch block.

    0 讨论(0)
提交回复
热议问题