Unhandled exceptions are exceptions that were not properly handled by the program causing the program to terminate. We will demonstrate here what will happen if a program detects an exception during runtime and there is no exception handling used. You will see how an exception can potentially destroy the flow or execution of your application. We are running our examples from the beginning up until now using Non-Debug mode. Running a program that contains no errors using Non-Debug or Debug modes have a minimal difference. Here, we will clearly see the difference of each mode.

Let’s create our test program. Create a new Console Application and name it ExceptionTest. Use the following code.

using System;
 
namespace UnhandledExceptionDemo
{
    public class Program
    {
        public static void Main()
        {
            int five = 5;
            int zero = 0;
 
            //Generate an exception by dividing 5 by 0
            int result = five / zero;
        }
    }
}

Example 1 – A Program without Exception Handling

 Dividing an integer by 0 is illegal and will cause a System.DivideByZeroException.

No Exception Handling (Non-Debug Mode)

Run the program in Non-Debug mode by hitting Ctrl+F5 shortcut. The program will successfully compile, but you will get the following error message.

Unhandled Exception: System.DivideByZeroException: Attempted to divide by zero.
 at ExceptionTest.Program.Main() in C:UsersTheUserAppDataLocalTemporary 
ProjectsExceptionTestProgram.cs:line 9

Then a window will prompt showing that the program was terminated.

Figure 1 – Unhandled Exception Window

As you can see the label “Unhandled Exception”. This is because the error was not handled properly because we did not use any exception handling techniques. These details are usually not needed by the one who will use your program.

No Exception Handling (Debug Mode)


There is a better way to see information about an unhandled exception. And that is by running the program in debug mode. You can go to Debug > Start Debugging to start Debug Mode. You can also hit the F5 key, or click the green play button located at the toolbar. It will now start debugging the program. During Debug Mode, Visual C# Express will stop executing and bring you to you code. The statement that produced the error will be highlighted in yellow and the Exception Assitant will show up.

The Exception Assistant is a helpful window that describes the exception that was unhandled and tries to give some tips on how you can troubleshoot or fix them. If the Exception Assistant is hidden, simply clicked again on the statement that threw the exception.