I am trying to implement my own Exception class in C#. For this purpose I have created a CustomException class derived from Exception.
class CustomException : Exception { public CustomException() : base() { } public CustomException(string message) : base(message) { } public CustomException(string format, params object[] args) : base(string.Format(format, args)) { } public CustomException(string message, Exception innerException) : base(message, innerException) { } public CustomException(string format, Exception innerException, params object[] args) : base(string.Format(format, args), innerException) { } }
Then I use it
static void Main(string[] args) { try { var zero = 0; var s = 2 / zero; } catch (CustomException ex) { Console.Write("Exception"); Console.ReadKey(); } }
I'm expecting I will get my exception but all I get is a standard DivideByZeroException. How can I catch a divide by zero exception using my CustomException class? Thanks.
The most basic way of returning an error message from a REST API is to use the @ResponseStatus annotation. We can add the error message in the annotation's reason field. Although we can only return a generic error message, we can specify exception-specific error messages.
In simple words, we can say that a User-Defined Exception or custom exception is creating your own exception class and throwing that exception using the 'throw' keyword. For example, MyException in the below code extends the Exception class.
Having custom exceptions - tailored to your specific use cases and that you can raise and catch in specific circumstances - can make your code much more readable and robust, and reduce the amount of code you write later to try and figure out what exactly went wrong.
In Python, users can define custom exceptions by creating a new class. This exception class has to be derived, either directly or indirectly, from the built-in Exception class. Most of the built-in exceptions are also derived from this class.
You can't magically change type of exception thrown by existing code.
You need to throw
your exception to be able to catch it:
try { try { var zero = 0; var s = 2 / zero; } catch (DivideByZeroException ex) { // catch and convert exception throw new CustomException("Divide by Zero!!!!"); } } catch (CustomException ex) { Console.Write("Exception"); Console.ReadKey(); }
First of all, if you want to see your own exception, you should throw
it somewhere in your code:
public static int DivideBy(this int x, int y) { if (y == 0) { throw new CustomException("divide by zero"); } return x/y; }
then:
int a = 5; int b = 0; try { a.DivideBy(b); } catch(CustomException) { //.... }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With