DEV Community

Ishaan Sheikh
Ishaan Sheikh

Posted on • Edited on

4 2

C# Exception Handling

Handling errors is an important part of programming which makes the program more user-friendly. In this tutorial, we'll learn about how we can handle exceptions in C#.

The throw keyword

The throw keyword is used to throw errors and stops the further execution of a program.


bool authorized = false;
if(authorized)
{
    // Your business logic here
}
else
{
    throw new Exception("Access denied");
}

Enter fullscreen mode Exit fullscreen mode

The above program throws an error as -

Unhandled exception. System.Exception: Access denied
Enter fullscreen mode Exit fullscreen mode

The throw keyword can be used with many types of exception classes. For example -


if(email == null)
{
    throw new ArgumentNullException("Email cannot be null");
}

Enter fullscreen mode Exit fullscreen mode

try-catch

The try-catch statement consist of a try block followed by one or more catch blocks.

try
{
    // Your code blocks
}
catch(Exception ex)
{
    throw new Exception("An error occured - " + ex);
}
Enter fullscreen mode Exit fullscreen mode

try-finally

This statement consist of a try block followed by a finally block which runs always after the try block.

try
{
    // Your code here...
}
finally
{
    // This block will run regardless of the result
}
Enter fullscreen mode Exit fullscreen mode

try-catch-finally

This statement consists of a try block followed by one or more catch blocks followed by a finally block which will run always regardless of the result. This is helpful in cases such as you have to free up the memory even if the program doesn't execute successfully.

try
{
    // Your main business logic
}
catch(Exception ex)
{
    throw new Exception("Error!");
}
catch(ArgumentNullException ex)
{
    throw new ArgumentNullException("Arg cannot be null");
}
...
// More catch blocks
...
finally
{
    // It will run regardless of the result
}
Enter fullscreen mode Exit fullscreen mode

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay