C# Systemexception Class

The SystemException class is a built-in exception class within the C# programming language. It is specifically designed to manage exceptions related to system operations. This class serves as the foundation for the system exception namespace. SystemException is employed to symbolize errors that arise while a program is running and are triggered by the Common Language Runtime (CLR).

The placeholder diagram is styled with a background gradient, rounded borders, padding, and center alignment. The icon within the diagram is large, and the text is smaller with a grey color.

In C#, the majority of predefined exceptions (like IndexOutOfRangeException, NullReferenceException, InvalidCastException, etc.) inherit from the SystemException class.

Syntax:

It has the following syntax:

Example

[SerializableAttribute]  

[ComVisibleAttribute(true)]  

public class SystemException : Exception

C# SystemException Class Example

Let's consider an example to demonstrate the SystemException class in C#.

Example

Example

using System;  

namespace CSharpProgram  

{  

    class Program  

    {  

        static void Main(string[] args)  

        {  

            try  

            {  

                int[] arr = new int[5];  

                arr[10] = 25;  

            }  

            catch (SystemException e)  

            {  

                Console.WriteLine(e);  

            }  

        }  

    }  

}

Output:

Output

System.IndexOutOfRangeException: Index was outside the bounds of the array.

Explanation:

In this instance, a collection of length 5 is utilized, yet the script attempts to retrieve data at position 10, exceeding the range. Subsequently, it triggers a System.IndexOutOfRangeException, a derivative of SystemException, that is captured within the catch block to exhibit the exception specifics.

Important Points about SystemException in C#

Several important points about SystemException in C# are as follows:

  • It represents the base class for all exceptions that are thrown by the runtime environment.
  • It offers standard constructors and properties to access error details, such as message, stack trace, and many inner exceptions.
  • It is not compulsory to create our own custom exceptions from SystemException. Instead, we can create them directly from Exception.

SystemExceptions encompasses a variety of elaborate constructors, attributes, and functions which are detailed in the table provided.

C# SystemException Constructors

The following table displays various constructors for SystemException in C#.

Constructors Description
SystemException() It is used to initialize a new instance of the SystemException class.
SystemException(SerializationInfo,StreamingContext) It is used to initialize a new instance of the SystemException class with serialized data.
SystemException(String) It is used to initialize a new instance of the SystemException class with a specified error message.
SystemException(String,Exception) It is used to initialize a new instance of the SystemException class with a specified error message and a reference to the inner exception that is the cause of this exception.

C# SystemException Properties

The following table displays various properties of SystemException types in C#.

Property Description
Data It is used to get a collection of key/value pairs that provide additional user-defined information about the exception.
HelpLink It is used to get or set a link to the help file associated with this exception.
HResult It is used to get or set HRESULT, a coded numerical value that is assigned to a specific exception.
InnerException It is used to get the Exception instance that caused the current exception.
Message It is used to get a message that describes the current exception.
Source It is used to get or set the name of the application that causes the error.
StackTrace It is used to get a string representation of the immediate frames on the call stack.
TargetSite It is used to get the method that throws the current exception.

C# SystemException Methods

The following table displays various kinds of SystemException methods in C#.

Method Description
Equals(Object) It is used to check that the specified object is equal to the current object or not.
Finalize() It is used to free resources and perform cleanup operations.
GetBaseException() It is used to get root exception.
GetHashCode() It is used to get hash code.
GetObjectData(SerializationInfo,StreamingContext) It is used to get object data.
GetType() It is used to get the runtime type of the current instance.
MemberwiseClone() It is used to create a shallow copy of the current Object.
ToString() It is used to create and return a string representation of the current exception.

C# SystemException Example using Catching Specific Exception

Let's consider a scenario to demonstrate handling a System Exception by capturing a particular exception in the C programming language.

Example

Example

using System;

class C# Tutorial

{

    static void Main()

    {

        try

        {

            string str = null;

            Console.WriteLine(str.Length); // NullReferenceException

        }

        catch (NullReferenceException ex)

        {

            Console.WriteLine("Caught a NullReferenceException: " + ex.Message);

        }

        catch (SystemException ex)

        {

            Console.WriteLine("Caught another SystemException: " + ex.Message);

        }

    }

}

Output:

Output

Caught a NullReferenceException: Object reference not set to an instance of an object

Explanation:

In this instance, we attempt to retrieve the Length attribute of an empty string, resulting in a NullReferenceException being raised. Initially, we implement a catch block tailored to address this specific scenario, while the subsequent catch block is designated for capturing any other system-level exceptions that might arise.

Conclusion

In summary, the SystemException class plays a crucial role as the foundational class for all runtime exceptions generated by the Common Language Runtime (CLR). While direct exception throwing may not be its primary function, it offers a means to identify numerous runtime errors. This class is frequently employed in handling specific exceptions, thereby enhancing error management and debugging capabilities.

SystemException FAQs

1) What is SystemException in C#?

In C#, the SystemException serves as the foundational class for all built-in exceptions within the .NET framework, representing potential errors that may arise while a program is running.

2) What are the typical subclasses that inherit from SystemException in the C# programming language?

In C#, there are several exceptions derived from SystemException. Some of them are as follows:

  • NullReferenceException
  • IndexOutOfRangeException
  • InvalidCastException
  • OutOfMemoryException

No, it is not recommended to directly use the SystemException in catch blocks in C#.

Yes, utilizing the SystemException within catch blocks in C# is permitted. Yet, it is generally advised to search for more precise exceptions like NullReferenceException or IndexOutOfRangeException.

4) Where can we define SystemException in C#?

In C#, we have the option to declare the SystemException within the System namespace located in the mscorlib.dll assembly.

5) Is it possible to deliberately throw a SystemException in C# code?

No, it is not possible to directly throw a SystemException in C#. Nevertheless, we have the option to throw specialized exception types or develop custom exceptions.

Input Required

This code uses input(). Please provide values below: