What is the main advantage to have specific exception classes , as we can have all exceptions in System.Exception class. Why would one use specific error handling class?
            Asked
            
        
        
            Active
            
        
            Viewed 376 times
        
    -4
            
            
        - 
                    3just came out of interview? – Vanity Slug - codidact.com Sep 25 '17 at 19:24
 - 
                    The answer really depends on your needs - sometimes you need things to be more granular. – Gratus D. Sep 25 '17 at 19:25
 - 
                    3Possible duplicate of [When should we create our own java exception classes?](https://stackoverflow.com/questions/22698584/when-should-we-create-our-own-java-exception-classes) – Vanity Slug - codidact.com Sep 25 '17 at 19:25
 - 
                    If you want to add specific structured information to your exception, a custom exception class allows you to add your own properties. It also allows consuming code to catch specifically that exception if the logic requires. – David Sep 25 '17 at 19:28
 - 
                    no alex its not a duplicate questions. Just wana know the fact that what is the use of specic exception classes such as IndexOutOfRangeException and ArgumentException – farrukhmask Sep 25 '17 at 19:29
 - 
                    1@farrukhmask: The linked potential duplicate question primarily answers exactly that. Did you read it? – David Sep 25 '17 at 19:30
 - 
                    4What is the main advantage to have classes at all, as we can have all objects as System.Object class? Why would one use specific classes at all? :) – Trioj Sep 25 '17 at 19:31
 
1 Answers
1
            
            
        Exception handlers work on a class by class basis. If you only had one exception class, you couldn't do this:
try
{
    //Do something that might raise different types of exceptions
}
catch(ArgumentException e1)  //Catch any exception that is an ArgumentException or one its derived types
{
    //Do something to handle the invalid argument
}
catch(NetworkException e2)  //Catch any exception that is a NetworkException or one of its derived types
{
    //Do something to handle the issue with the network
}
catch(Exception e3)
{
    //Do something to log the unexpected exception
    throw;
}
Note that you should not catch the base exception unless the only thing you are doing is logging it and rethrowing.
        John Wu
        
- 50,556
 - 8
 - 44
 - 80