In this article I will explain with an example, how to handle the exceptions in ASP.Net Core.
Understanding Exceptions
Exception Handling is a procedure to handle the exception which occurred during the execution of a program.
In .Net, errors are represented as exceptions, which are objects derived from the base class System.Exception.
There are different types of exceptions which includes ArgumentNullException, InvalidOperationException, and IOException etc.
When an error occurs, an exception is thrown, and if not caught, it terminates the application.
Note: Most user says that Runtime Errors are Exceptions which is not true. Exceptions are classes that are responsible for termination of the program when runtime errors occur.
What happens if an Exception is occurred in the Program in .Net?
When an Exception is occurred in .Net, the program execution is terminated.
It means that, the statements placed after the exception causing statements are not executed but the statements placed before are executed by Common Language Runtime (CLR).
Handling Exception Mechanism
In order to handle the exception you need to make use of Try-Catch block.
Following is the syntax of Try-Catch block.
Try – The try statement is used to catch exceptions, which might occur during execution of code.
Catch – The catch statement is used to handle the exception.
Finally – The finally statement is used to execute code regardless of whether an exception is thrown. It is used for resource cleanup.
public class HomeController : Controller
{
public IActionResult Index()
{
try
{
// Code that might throw Exception.
}
catch (Exception ex)
{
// Handle Exception.
}
finally
{
}
return View();
}
}
Screenshot
Handling Exceptions
In the following example, an exception is raised by converting a string value to integer inside a Try-Catch block.
This type of exception is called FormatException.
The raised Exception is caught in the Catch block.
public class HomeController : Controller
{
public IActionResult Index()
{
try
{
// Code that might throw Error.
int i = int.Parse("Mudassar");
}
catch (Exception ex)
{
}
finally
{
}
return View();
}
}
Screenshot
Handling Multiple Types of Exception
In the following example, instead of catching general exceptions, specific exceptions are handled. This allows user to respond appropriately to different error conditions.
Note: The Exception class must be in the last catch block, else it will throw compilation error.
public class HomeController : Controller
{
public IActionResult Index()
{
try
{
// Code that might throw Exception.
}
catch (ArgumentNullException ex)
{
// Handle null argument Exception.
}
catch (IOException ex)
{
// Handle I/O Exception.
}
catch (Exception ex)
{
// Handle any other Exceptions.
}
finally
{
}
return View();
}
}
Screenshot
Example
In the following example, an exception is raised when trying to open the file that is not present in the specified path i.e. inside the Files folder present in the wwwroot folder (directory).
This type of exception is called FileNotFoundException.
The raised Exception is caught in the 2nd Catch block.
public class HomeController : Controller
{
private IWebHostEnvironment Environment;
public HomeController(IWebHostEnvironment _environment)
{
this.Environment = _environment;
}
public IActionResult Index()
{
FileStream fileStream = null;
try
{
// Code that might throw Error.
string filePath = Path.Combine(this.Environment.WebRootPath, "Files\\Sample.txt");
fileStream = new FileStream(filePath, FileMode.Open);
}
catch (ArgumentNullException ex)
{
// Handle null argument Exception.
}
catch (FileNotFoundException ex)
{
// Handle file not found Exception.
}
catch (Exception ex)
{
// Handle any other Exceptions.
}
finally
{
if (fileStream != null)
{
fileStream.Close();
}
}
return View();
}
}
Screenshot
Downloads