C# Tutorial
C# String
C# Array
C# Flow Control
C# Class and Object
C# Inheritance
C# Interface
C# Collection
C# Generic
C# File I/O
C# Delegate and Event
C# Exception
C# Process and Thread
C# ADO.NET Database Operations
The Exception
class in C# is the base class for all exceptions. It provides a base set of properties and methods that can be used to handle exceptions in a consistent manner. In this tutorial, we will discuss some common properties and methods of the Exception
class, and show how to use them when handling exceptions.
Here are some common properties of the Exception
class that provide information about an exception:
Message
: A human-readable description of the error.InnerException
: The Exception
instance that caused the current exception, if any.StackTrace
: A string representation of the immediate frames on the call stack.Source
: The name of the application or the object that caused the error.TargetSite
: The method that threw the current exception.When catching an exception, you can access its properties to obtain more information about the error:
using System; namespace ExceptionClassTutorial { class Program { static void Main(string[] args) { try { Console.WriteLine("Trying to divide by zero..."); int result = Divide(10, 0); // Throws a DivideByZeroException } catch (Exception ex) { Console.WriteLine("Message: " + ex.Message); Console.WriteLine("Source: " + ex.Source); Console.WriteLine("StackTrace: " + ex.StackTrace); Console.WriteLine("TargetSite: " + ex.TargetSite); } } static int Divide(int a, int b) { return a / b; } } }
In this example, we catch a DivideByZeroException
thrown by the Divide()
method and access its properties to display information about the error.
Sometimes, an exception might be caused by another exception, forming a chain of exceptions. In such cases, you can use the InnerException
property to access the underlying exception:
using System; using System.IO; namespace InnerExceptionTutorial { class Program { static void Main(string[] args) { try { ReadFile("non_existing_file.txt"); } catch (Exception ex) { Console.WriteLine("Outer exception: " + ex.Message); if (ex.InnerException != null) { Console.WriteLine("Inner exception: " + ex.InnerException.Message); } } } static void ReadFile(string filename) { try { using (StreamReader reader = new StreamReader(filename)) { string content = reader.ReadToEnd(); } } catch (FileNotFoundException ex) { throw new Exception("Error occurred while reading the file.", ex); } } } }
In this example, we catch a FileNotFoundException
thrown by the StreamReader
constructor and wrap it in a custom exception using the InnerException
property. When handling the custom exception, we can access the inner exception's properties to get more information about the root cause of the error.
In this tutorial, we've discussed some common properties of the Exception
class and how to use them when handling exceptions in C#. By leveraging the Exception
class properties, you can create more informative error messages and handle exceptions more effectively.
Handling exceptions in C#:
using System; class Program { static void Main() { try { // Code that may cause an exception int result = 10 / 0; // This will throw a DivideByZeroException } catch (Exception ex) { // Handle the exception Console.WriteLine($"Exception caught: {ex.Message}"); } } }
Custom exceptions in C#:
Exception
base class.using System; // Custom exception class public class CustomException : Exception { public CustomException(string message) : base(message) { } } class Program { static void Main() { try { throw new CustomException("Custom exception occurred"); } catch (CustomException ex) { Console.WriteLine($"Custom exception caught: {ex.Message}"); } } }
C# catch block with multiple exceptions:
catch
block can handle multiple types of exceptions by listing them in the catch parameter.using System; class Program { static void Main() { try { // Code that may cause exceptions int[] numbers = { 1, 2, 3 }; Console.WriteLine(numbers[5]); // This will throw an IndexOutOfRangeException } catch (IndexOutOfRangeException ex) { Console.WriteLine($"Index out of range: {ex.Message}"); } catch (Exception ex) { Console.WriteLine($"General exception caught: {ex.Message}"); } } }
Exception filtering in C#:
catch
block should execute.using System; class Program { static void Main() { try { int result = Divide(10, 0); } catch (Exception ex) when (ex is DivideByZeroException) { Console.WriteLine($"Divide by zero exception caught: {ex.Message}"); } catch (Exception ex) { Console.WriteLine($"General exception caught: {ex.Message}"); } } static int Divide(int a, int b) { if (b == 0) { throw new DivideByZeroException("Cannot divide by zero."); } return a / b; } }
C# nested try-catch blocks:
try-catch
blocks allow handling exceptions at different levels of code hierarchy.using System; class Program { static void Main() { try { // Outer try-catch block Console.WriteLine("Outer try block"); try { // Inner try-catch block Console.WriteLine("Inner try block"); throw new Exception("Inner exception"); } catch (Exception innerEx) { Console.WriteLine($"Inner exception caught: {innerEx.Message}"); } // Code after inner try-catch block Console.WriteLine("Code after inner try block"); } catch (Exception outerEx) { Console.WriteLine($"Outer exception caught: {outerEx.Message}"); } } }
C# finally block usage:
finally
block is used to specify code that will be executed whether an exception occurs or not.using System; class Program { static void Main() { try { // Code that may cause an exception int result = 10 / 0; // This will throw a DivideByZeroException } catch (Exception ex) { Console.WriteLine($"Exception caught: {ex.Message}"); } finally { // Code in the finally block will always be executed Console.WriteLine("Finally block executed"); } } }