Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are All Exception Types Caught Under Plain Old "Exception"?

Tags:

c#

exception

I'm just trying to understand this a little better.

I understand there are many different exception types, and according to some reading I've done, all exception types are caught by Exception. First of all, can I be assured that this is true?

try{
    ...
}
catch(Exception x){
    //No matter what fails in the try block, x 
    //will always have a value since all exception
    //types are caught under Exception? I guess
    //What I really want to know, is will this ever
    //Fail?
}
catch(SystemException x){
    //This code will never execute since all 
    //exceptions are caught in the first catch?
}

Next, how does this catching hierarchy work? If Exception is at the top, is every other exception type one level under Exception, or are there multiple type tiers, like if Exception is the parent of ExceptionSomething, which is the parent of ExceptionSomethingElse?

addendum:

Or if we have code like this:

try{
    ...
}
catch(SystemException x){
    //If there is an exception that is not a SystemException
    //code in this block will not run, right (since this is 
    //looking specifically for SystemExceptions)?
}
like image 389
sooprise Avatar asked Dec 03 '22 02:12

sooprise


2 Answers

It actually depends on your .NET version and configuration. In C++/CLI you can throw anything; it doesnt have to be an Exception. In 1.1 (IIRC) ou could only catch these with a catch block like:

catch {...}

Which isn't very helpful - you can't see what happened. In 2.0 (IIRC) by default such exceptions are automatically wrapped up inside a dummy RuntimeWrappedException subclass. However, for compatibility you can turn this off. I beg you: don't :)

like image 168
Marc Gravell Avatar answered Dec 20 '22 22:12

Marc Gravell


Yes, this works because all standard exceptions inherit from Exception.

Your code will work but you'll need to put the handler for Exception after all specialized exception types. (The first matching handler will execute.)

Exceptions that do not inherit from Exception would not be caught because they are not the specified type. But the .NET exception classes all inherit from this base class.

Some people don't think it's a good idea but I generally only catch Exception, unless I want special handling for a particular exception type.

like image 40
Jonathan Wood Avatar answered Dec 21 '22 00:12

Jonathan Wood