Try Catch or If statement?

前端 未结 10 1849
北恋
北恋 2020-12-15 17:47

if you think there is a possibility of getting a null pointer exception, should you use an if statement to make sure the variable is not null, or should you just catch the e

相关标签:
10条回答
  • 2020-12-15 18:31

    using try catch for the statements is not an good idea. because when you use try catch them it seems that if some error comes the code will not turninate the application. but if you are sure about what kind of error can come you can tap the error at that point. that will not produce any unknown errors. for example.

    string name = null;
    

    here i am going to use the name variable and i am sure that this will throw Null Refrance Error .

    try
    {
    Console.writeLine("Name ={0}",name);
    }
    catch (NullRefranceException nex)
    {
    //handle the error 
    }
    catch(Exception ex)
    {
     // handle error to prevent application being crashed. 
    }
    

    This is not a good practice while you can handle this kind of error and make your code more readable. like.

    if(name !=null)
        Console.writeLine("Name ={0}",name);
    
    0 讨论(0)
  • 2020-12-15 18:33

    Well. Exceptions are just that. Exceptions. They are thrown when something unforseen has happened and should not be part of the normal program flow.

    And that's what is happening here. You expected the argument to be specified when it's not. That is unexpected and you should therefore throw your own exception informing the user of that. If you want to get bonus points you can also include the reason to WHY the argument must be specified (if it's not obvious).

    I've written a series of posts about exceptions: http://blog.gauffin.org/2013/04/what-is-exceptions/

    0 讨论(0)
  • 2020-12-15 18:33

    Its always better to use Try Catch other than if else Here Exceptions are two types namely handled and UN-handled exceptions Even if u want to handle some function when the Exception u can handle it...

    Handled exception always allows you to write some implementations inside the Catch block Eg. An Alert Message, A new Function to handle when such exception occurs.

    0 讨论(0)
  • 2020-12-15 18:35

    I would say ALWAYS use logic to catch the exception, not try/catch.

    Try/Catch should be used when you validate but some strange thing happens and something causes an error so you can handle it more gracefully.

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