C# - Exception

Created:2019-06-19  Last modified:2019-06-19


  1. Syntax

    1. Compared with Java

      C# only has try, catch, finally, throw; but java also has throws that mark on method signature.

    2. Example

                  try{
      
                  }catch(Exception ex){
      
                  }finally{
                      // finally is always executed, even if catch statement also throws exception.
                  }
              
    3. Finally throws exception

      Exception is not stacked, meaning if the finally also throws exception, then it will override the catch throwed exception.

                      try{
                          throw KeyNotFoundException("key not found");
                      }catch(Exception ex){
                          throw new AggregateException("", new Exception("Resource Not found."));
                      }finally{
                          throw new IndexOutOfRangeException("Out Of Range");
                      }
                      // the received exception by caller is IndexOutOfRangeException, AggregateException is overriden.
                  
    4. Shorthand

                      try{
      
                      }catch{
      
                      }
                      // same
                      try{
      
                      }catch(Exception e){
      
                      }
      
                      // re-throw the same exception;
                      catch(Exception ex){
                          throw ex;
                      }
                      // same
                      catch{
                          throw;
                      }
                  
  2. Organization

                                Exception (namespace: System);
                                    |
                                    |
                                    |
                                SystemException (system)                        AggregateException             Developer defined ApplicationException;
                                    |
                                ArgumentException
                                IndexOutOfRangeException
                                KeyNotFoundException(System.Collections.Generic)
                                NotImplementException
                                NullReferenceException
                                IOException (System.IO)
                                    |
                                FileNotFoundException