salocinx
salocinx

Reputation: 3823

Why is exception not caught?

The following code generates a NullReferenceException, but is not caught by the try block (in both Debug and Release mode):

using System;

namespace ExceptionTest {
    public class Program {
        public static void Main(string[] args) {
            String text = null;
            try {
                if (text.Equals("t1")) {
                    Console.WriteLine("r1");
                } else {
                    Console.WriteLine("r2");
                }
            } catch(Exception ex) {
                Console.WriteLine("Exception catched!");
            }
        }
    }
}

Instead the program breaks and the offending line is highlighted:

enter image description here

Why?

Update: Textual representation of the exception as suggested by Scott:

System.NullReferenceException occurred
  HResult=-2147467261
  Message=Object reference not set to an instance of an object.
  Source=ExceptionTest

Upvotes: 1

Views: 2333

Answers (3)

Scott Chamberlain
Scott Chamberlain

Reputation: 127603

It happens because you have this box checked

enter image description here

That makes your debugger break before it gets to the catch block, if you hit continue you would see it continue in to the catch. If you uncheck the box you can re-enable it under your "Exception Settings" window found via the Debug -> Windows -> Exception Settings dropdown menu. The section "Common Language Runtime Exceptions" contains the NullRefrenceException option.

enter image description here

Upvotes: 4

Lifu Huang
Lifu Huang

Reputation: 12869

If you are using Visual Studio 2015:

Debug->Windows->Exception Settings

Search for NullReferenceException, and uncheck that.

Upvotes: 2

Timon Post
Timon Post

Reputation: 2879

On the example image under Exception settings: turn of the checkbox.

By doing this it will not break when a null reference exception is thrown.And the catch would catch the Exception.

Upvotes: 3

Related Questions