List of exceptions that CAN'T be caught in .NET

What is the list of exceptions that CAN'T be caught in .NET? Or where can I find such a list?


Solution 1:

The only exception that cannot be caught directly is (a framework thrown) StackOverflowException. This makes sense, logically, as you don't have the space in the stack to handle the exception at that point. From the docs:

Starting with the .NET Framework version 2.0, a StackOverflowException object cannot be caught by a try-catch block and the corresponding process is terminated by default.

ThreadAbortException can be caught, but will always get re-raised, so has unique behavior. From the docs:

ThreadAbortException is a special exception that can be caught, but it will automatically be raised again at the end of the catch block.

Also note that some AccessViolationException instances are corrupted state exceptions, and may not get handled by default. These can be handled, but require extra handling via attributes. For details, see Handling Corrupted State Exceptions.

Solution 2:

NullReferenceException can certainly be caught. Where did you get the idea from?

A try {} catch {} will catch non managed exceptions as well as managed ones (note that there is not exception clause on the catch).

The only one that cannot be caught is StackOverflowException, and TreadAbortException gets rethrown at the end of the catch.

Solution 3:

ThreadAbortException

Note:

ThreadAbortException is a special exception that can be caught, but it will automatically be raised again at the end of the catch block. When this exception is raised, the runtime executes all the finally blocks before ending the thread.

Solution 4:

Well there are some exceptions that will always be re-thrown even if you catch them. StackOverflowException is the only ones i can think of atm though. possibly ThreadAbortedException.

Solution 5:

Try this... (Tested on .NET Core 2.0)

System.Runtime.Serialization.FormatterServices.GetUninitializedObject(typeof(Type).GetType()).ToString()

A System.ExecutionEngineException that ignores all try/catch/finally blocks is thrown, even though it was deprecated saying the runtime NO LONGER THROWS this type of excpetion. Weird, eh?

The reason for this might be typeof(Type).GetType() returns typeof(System.RuntimeType) which is an internal type and a runtime intrinsic. There are validation of arguments by System.Runtime.Serialization.FormatterServices.GetUninitializedObject regarding these types like typeof(string), but the developers probably forgot to check this non-public type. As a result, an invalid System.RuntimeType is returned. When ToString is called, the invalid state causes the runtime to crash.