DEV Community

Cover image for Throw Exception in C#
Hootan Hemmati
Hootan Hemmati

Posted on

Throw Exception in C#

Image description
Hello, today we want to talk about the keyword Throw and see where this word came from and what it does.
As we know, in C# language, we have a command called try-catch, which means that if an error occurs in the code, we can use catch to catch it and perform our desired operation.
After that, the creators of programming languages thought that if a programmer wants to call an error in a specific situation, he knows that he should call an error and throw it so-called. What should he do in the program?

This is where they came up with this magical idea and created the Throw keyword so that any programmer can call the error he wants in the program at any time, and the program will realize that there is an error.

For example, you can see in the code above that, first of all. We defined an object of Student in the program's Main method, whose value is equal to null.

Student std = null;
Enter fullscreen mode Exit fullscreen mode

Now, in the try block, we see that we called the PrintStudentName method and null as the input of that object. We pass what we made to it.

try
{
  PrintStudentName(std);
}
Enter fullscreen mode Exit fullscreen mode

The exciting thing is that we came to the PrintStudentName method and checked that if our input were null, it would generate a NullReferenceException error and also show a message that we would later find out was related to an error that we bred ourselves.

private static void PrintStudentName( Student std)
{
    if (std  == null)
        throw new NullReferenceException("Student object is null.");

    Console.WriteLine(std.StudentName);
}
Enter fullscreen mode Exit fullscreen mode

You can also see this error text that we entered in the constructor method of this class.

Error text:
The student object is null.

After we have done this, the program immediately understands that an error has occurred, and we exit the PrintStudentName method. Because we generated an error in the same line where we caused the error, we exit the method from the same line, and the method is not executed for the rest of the lines.
Where do we go when an error occurs in the program if we have managed it? Well done, that's right, we go to the catch block.
We also wrote in the catch block that it receives an Exception input (which, as you know, is the father of all errors, and we give it special respect) and prints the message related to that error.

catch(Exception ex)
{
  Console.WriteLine(ex.Message );
}
Enter fullscreen mode Exit fullscreen mode

We learned this simple matter very well together.

Top comments (0)