Ask Your Question
2

How can one explicitly define the exceptions that are thrown in C#?

asked 2021-11-01 11:00:00 +0000

bukephalos gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2021-06-21 09:00:00 +0000

woof gravatar image

To explicitly define the exceptions that are thrown in C#, you can use the try-catch block and specify the type of exception that you want to catch. For example:

try {
  // code that may throw an exception
} catch (ArgumentNullException ex) {
  // handle exception specifically for ArgumentNullException
} catch (Exception ex) {
  // handle other exceptions
}

In this example, the first catch block will only catch exceptions of type ArgumentNullException, while the second catch block will catch all other exceptions. You can also create your own custom exceptions by inheriting from the Exception class and defining your own properties and methods.

Here's an example:

public class CustomException : Exception {
  public CustomException(string message) : base(message) { }

  public int ErrorCode { get; set; }

  public void LogException() {
    // custom code to log the exception
  }
}

In this example, we created a custom exception called CustomException that has an ErrorCode property and a LogException method. We can then throw this exception in our code and catch it as we would any other exception:

try {
  throw new CustomException("Something went wrong") {
    ErrorCode = 500
  };
} catch (CustomException ex) {
  Console.WriteLine("Error Code: " + ex.ErrorCode);
  ex.LogException();
} catch (Exception ex) {
  // handle other exceptions
}
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2021-11-01 11:00:00 +0000

Seen: 11 times

Last updated: Jun 21 '21