Search code examples
c#exceptiontry-catchsqlexceptioncatch-block

How to check the types of Exceptions thrown in a catch block?


I have something like this:

catch (Exception ex)
 {
      if (ex is "Exception Type")
      {

      }
      else if (ex is SqlException)
      {

      }
      else if 
      {
        ...
        ...
        ...
 }

Is this right in C# and what does the is mean anyway, which is its role or is there another way?


Solution

  • Yes, there is another way. By calling the specific exceptions that could possibly occur when running a block of code:

    try {
       // Do something
    }
    catch(SqlException ex) {
    
    }
    catch(AnotherException ex) {
    
    }
    

    Then it is very important to start with the most specific exception and work your way towards a general exception.