What will be the output of this C# program when it throws and catches a custom exception?
using System; class MyCustomException : Exception { public MyCustomException(string message) : base(message) {} } class Program { static void Main() { try { throw new MyCustomException("Oops, something went wrong!"); } catch (MyCustomException ex) { Console.WriteLine(ex.Message); } } }
Look at what ex.Message prints when caught.
The custom exception inherits from Exception and passes the message to the base class. Catching it and printing ex.Message outputs the message string.
Why do programmers create custom exception classes instead of using only built-in exceptions?
Think about how custom exceptions help in understanding errors better.
Custom exceptions allow programmers to signal specific problems related to their application, making error handling clearer and more precise.
What error will this code produce when compiled?
using System; class MyException : Exception { public MyException(string message) { base.Message = message; } } class Program { static void Main() { throw new MyException("Error occurred"); } }
Check if Message property can be assigned directly.
The Message property in Exception is read-only. You must pass the message to the base constructor instead of assigning it.
Which option correctly defines a custom exception class that supports serialization?
Serialization requires the [Serializable] attribute and a protected constructor calling base.
Option C correctly adds the [Serializable] attribute and implements the protected constructor calling the base constructor with SerializationInfo and StreamingContext.
Given this code, how many exceptions will be caught and printed?
using System; class CustomEx : Exception {} class Program { static void Main() { int count = 0; try { throw new CustomEx(); } catch (Exception) { count++; try { throw new CustomEx(); } catch (CustomEx) { count++; } } Console.WriteLine(count); } }
Count increments each time an exception is caught.
The first throw is caught by catch(Exception), incrementing count to 1. Then inside that catch, another throw is caught by catch(CustomEx), incrementing count to 2. So total printed is 2.