What's a C# Throw Exception?

How to Throw C# Exceptions Like a Major League Pro: Examples, Best Practices, and Everything You Need to Know

Stackify Developer Tips, Tricks & Resources Leave a Comment

Practically everyone who has ever used a web page or an app has encountered an exception at one point or another, but they probably didn’t realize what it was. Exceptions are pretty common ways to handle unexpected inputs but are they always the right way to handle such problems? In this post, we’ll take a closer look at C# exceptions, an example, and cover some best practices for when to throw exceptions and when it might be smart to consider another option.

What Does “Throw Exception” Mean?

An exception is an event that occurs during the execution of a program. It disrupts the normal flow of instructions. This is perhaps the simplest definition of an exception.

An exception is basically a problem occurring while a program is being executed.  It is the response of the OS to any exceptional computing which results in error, and there is no direction within the program about what should be done. In programming jargon, developers say a program “throws an exception,” hence the term “throw exception”. Throw is also a keyword in C#.

Exception handlers are shortcodes written to handle specific errors that may occur during execution. Control is transferred to the handlers when errors occur, and the handlers tell the program what to do.

There are four main constructs used within programs to handle exceptions – try, catch, finally, and throw. These keywords are specific to C#. Other programming languages may use different keywords, but the basic logic is generally the same. Let’s take a look at a hypothetical example to understand this better.

A Hypothetical Example: C# Throw Exception

Let’s assume that we are calculating the average grades for students. Further, we’ll assume that for a particular subject not a single student sat for the exam. In this case, the divisor would become zero. If this situation occurs and there is no handler, the program would crash. However, developers usually foresee this possibility and check for zero divisors. A developer would enter code to handle the error by displaying an error message and bringing the program to a logical end.

StackOverflow provides some example code for handling such an error.


Free Download

namespace nsDivZero
{
    using System;
    public class DivZero
    {
        static public void Main ()
        {
            // Set an integer equal to 0
            int IntVal1 = 0;
            // and another not equal to zero
            int IntVal2 = 57;
            try
            {
                Console.WriteLine ("{0} / {1} = {2}", IntVal2, IntVal1, IntResult (IntVal2, IntVal1) / IntResult (IntVal2, IntVal1));
            }
            catch (DivideByZeroException e)
            {
                Console.WriteLine (e.Message);
            }
            // Set a double equal to 0
            double dVal1 = 0.0;
            double dVal2 = 57.3;
            try
            {
                Console.WriteLine ("{0} / {1} = {2}", dVal2, dVal1, DoubleResult (dVal2, dVal1));
            }
            catch (DivideByZeroException e)
            {
                Console.WriteLine (e.Message);
            }
        }
        static public int IntResult (int num, int denom)
        {
            return (num / denom);
        }
        static public double DoubleResult (double num, double denom)
        {
            return (num / denom);
        }
    }
}

Quite simply, this code divides one variable by another and stores the result in a third variable. This division is performed in the try{} part of the exception handler. In the event that the value of the divisor is zero, control is automatically transferred to the catch{} part, which displays a message for the user and terminates the program.

The general syntax for catching an exception is to use a try-catch combination with the statements that may throw an exception contained within the try{} block and the error handling contained within the catch{} block.

Benefits of Exceptions

The advantage of throwing exceptions lies the answer to the question, “What is your program doing?” In the above example, for instance, you’d probably prefer to continue to the next set of numbers rather than abort the program. In this case, preventing the divisor from becoming zero at any point may be better than throwing an exception when an error occurs.

If, however, you are attempting to store data in a file, and the file is non-existent, such an error cannot be prevented. Therefore, it becomes necessary to throw an exception and handle the error logically, letting the user know that “A system Error Has Occurred” or that the “File Does Not Exist.”

You might say that prevention is a better alternative. But if for instance, you check for zero value every time a result is generated, it’s one additional step for runtime, meaning it takes that much longer for the program to execute. Where the data is large, this can make a significant difference, and exception handlers may become necessary.

The best approach to handling an error is a decision that must be made by the developer.

Best Practices for Throwing & Catching C# Exceptions

Exceptions can be handled in different ways. Let’s say you’re storing the results of an equation into an array. In this case, you may check for zero value at the time the result is generated, and avoid storing zero in your array. That way, no exception is likely to be thrown.

It’s up to you as a developer to choose how to handle exceptions within the code. According to Blackwasp, two great uses of the exception handler are:

  1. When an invalid value (such as zero) is passed to a method.
  2. When a method fails to run (perhaps because previous steps such as opening a file have not been completed).

Infoworld, on the other hand, states returning exceptions as the result of a method is bad programming practice. Exceptions are thrown to the next higher level in the hierarchy. Handling exceptions at lower levels may complicate the code and make it difficult to trace the error. Infoworld suggests that exceptions should be handled as high as possible in the hierarchy.

MSDN suggests creating “human” messages rather than throwing exceptions from the ApplicationException class, which is what the “throw” statement does. The ApplicationException class does not provide the cause of the error.

If, however, you don’t want to create your own error handler, it’s better to throw the exception from the exception class simply. Infoworld advocates logging the sequence of events that led to the exception rather than just the exception itself.

The try-catch-throw construct of C# is an extremely useful tool for trapping errors and preventing an application from crashing. It provides a systematic way to let both the user and the developer know what went wrong and why.

However, exceptions are just that – exceptions – and should be used sparingly. If you expect an error to recur a number of times, it’s better to use the IF construct to avoid its occurrence rather than throw an exception. Exceptions are for errors that cannot be trapped within the normal flow of the program, such as file open errors, IO errors, and so forth.

Our advice? Take all possibilities into consideration before deciding to throw exceptions.

About Stackify

Stackify provides developer teams with unparalleled visibility and insight into application health and behavior, both proactively in a monitoring role as well as reactively in a troubleshooting role, while eliminating the need to login to servers and other resources in order to investigate application problems.