C# SystemException
In C#, SystemException
is the base class for all exceptions that are defined in the core .NET Framework and provides the basic functionality of an exception. In this tutorial, we'll discuss how to use SystemException
in C#.
Syntax
The syntax for using SystemException
in C# is as follows:
try {
// code that may throw an exception
} catch (SystemException e) {
// code to handle the exception
}
The SystemException
class is caught in the catch block, with its reference variable named e
.
Example
Let's say we want to create a method that accepts a string argument and throws an exception if the string is null or empty. Here's how we can implement it:
public void ValidateString(string input) {
if (string.IsNullOrEmpty(input)) {
throw new SystemException("String is null or empty!");
}
}
Now, we can call the ValidateString
method and handle the SystemException
:
try {
ValidateString(null);
} catch (SystemException e) {
Console.WriteLine(e.Message); // Output: String is null or empty!
}
Output
When we run the example code above, the output will be:
String is null or empty!
This is because the ValidateString
method was called with a null string argument, which throws a SystemException
. The SystemException
is then caught in the catch block and its message is printed to the console.
Explanation
In the example above, we created a method called ValidateString
that accepts a string argument and throws a SystemException
if the string is null or empty. We then called the ValidateString
method with a null string argument, which threw a SystemException
. The SystemException
was then caught in the catch block and its message was printed to the console.
Use
SystemException
can be used to handle any type of exception that is defined in the core .NET Framework. You can use it to catch exceptions that are thrown by other methods, classes, or libraries.
Important Points
SystemException
is the base class for all exceptions that are defined in the core .NET Framework.- Always catch the specific exception type when possible, instead of catching
SystemException
. - Use
SystemException
to catch exceptions that are not specific to any particular type of exception.
Summary
In this tutorial, we discussed how to use SystemException
in C#. We covered the syntax, example, output, explanation, use, and important points of SystemException
in C#. With this knowledge, you can now catch exceptions that are defined in the core .NET Framework with SystemException
and handle them in your code.