Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the best way to raise an exception in C#?

Tags:

c#

exception

I traditionally deploy a set of web pages which allow for manual validation of core application functionality. One example is LoggerTest.aspx which generates and logs a test exception. I've always chosen to raise a DivideByZeroException using an approach similar to the following code snippet:

try {    int zero = 0;    int result = 100 / zero; } catch (DivideByZeroException ex) {    LogHelper.Error("TEST EXCEPTION", ex); } 

The code works just fine but I feel like there must be a more elegant solution. Is there a best way to raise an exception in C#?

like image 201
Ben Griswold Avatar asked Dec 03 '08 00:12

Ben Griswold


People also ask

How do you handle exception in C?

As such, C programming does not provide direct support for error handling but being a system programming language, it provides you access at lower level in the form of return values. Most of the C or even Unix function calls return -1 or NULL in case of any error and set an error code errno.

What are exceptions in C?

An exception is a problem that arises during the execution of a program. A C++ exception is a response to an exceptional circumstance that arises while a program is running, such as an attempt to divide by zero. Exceptions provide a way to transfer control from one part of a program to another.

What is used to raise an exception?

The raise keyword is used to raise an exception. You can define what kind of error to raise, and the text to print to the user.

How do you throw an exception correctly?

Throwing an exception is as simple as using the "throw" statement. You then specify the Exception object you wish to throw. Every Exception includes a message which is a human-readable error description. It can often be related to problems with user input, server, backend, etc.


1 Answers

try {   throw new DivideByZeroException(); } catch (DivideByZeroException ex) {   LogHelper.Error("TEST EXCEPTION", ex); } 
like image 52
GalacticCowboy Avatar answered Oct 13 '22 18:10

GalacticCowboy