Introduction
Custom exception classes let you create your own error types to better explain problems in your program.
Jump into concepts and practice - no test required
public class MyCustomException : Exception { public MyCustomException() { } public MyCustomException(string message) : base(message) { } public MyCustomException(string message, Exception inner) : base(message, inner) { } }
public class AgeException : Exception { public AgeException(string message) : base(message) { } }
public class FileMissingException : Exception { public string FileName { get; } public FileMissingException(string fileName) : base($"File {fileName} is missing.") { FileName = fileName; } }
using System; public class AgeException : Exception { public AgeException(string message) : base(message) { } } class Program { static void CheckAge(int age) { if (age < 18) { throw new AgeException("Age must be at least 18."); } Console.WriteLine("Age is valid."); } static void Main() { try { CheckAge(15); } catch (AgeException ex) { Console.WriteLine($"Custom error caught: {ex.Message}"); } } }
custom exception class in C#?MyException in C#?Exception to behave like exceptions.base(message) to pass the error message properly.class MyException : Exception { public MyException(string message) : base(message) {} }
try {
throw new MyException("Error happened");
} catch (MyException ex) {
Console.WriteLine(ex.Message);
}MyException with message "Error happened".MyException and prints ex.Message, which is "Error happened".class MyError : Exception {
public MyError(string msg) {
base(msg);
}
}public MyError(string msg) : base(msg) {}, not calling base(msg); inside the constructor body.InvalidAgeException that should be thrown when a user's age is less than 0 or greater than 120. Which of the following code snippets correctly defines and uses this exception?Exception and has a constructor calling base(msg) to pass the message.