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");
}
The above program throws an error as -
Unhandled exception. System.Exception: Access denied
The throw
keyword can be used with many types of exception classes. For example -
if(email == null)
{
throw new ArgumentNullException("Email cannot be null");
}
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);
}
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
}
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
}
Top comments (0)