Link to home
Start Free TrialLog in
Avatar of pzozulka
pzozulka

asked on

C#: How to manually throw exceptions

The code I'm working with has an existing try catch block. The catch block is below. In the try block, I need to manually throw an exception if a condition is met.

catch (Exception ex)
{
      ...
      ImportStatus.Append(ex.Message);
      ...
}

What is the correct way to throw an exception? Will this work? The reason I ask is because the catch block seems to accept a single parameter of type Exception. But I'm passing a string, so that's why I'm a bit confused on how to properly throw an exception with a string message.

string errorMsg = "This is an error.";
throw new Exception(errorMsg);

Open in new window

Avatar of Kyle Abrahams, PMP
Kyle Abrahams, PMP
Flag of United States of America image

When used in a try / catch the exception is if one of your lines of code throws an error:

eg

try

{
   int x = 0;
   int y = 10 / x;
}
 catch (Exception ex)
{
   //ex will be divide by 0 generated by the second line.  
}

You can create your own exceptions if you have custom classes, throwing them for others to catch.
Avatar of pzozulka
pzozulka

ASKER

Right, but what if I say the following in the try block:
throw new Exception("Address length is too long");

Open in new window

Will this be caught by the catch block?
ASKER CERTIFIED SOLUTION
Avatar of Kyle Abrahams, PMP
Kyle Abrahams, PMP
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
This is an existing try catch block that I'm not allowed to alter at the moment as it has nothing to do with the requested code/functionality changes.

Having said that, I'm a bit rusty with exceptions. Kyle, I'm not sure what you meant by
Note that the first string is the exception message,
.

If my catch block only accepts a single parameter, as in: catch(Exception ex), then how is it that passing a string by doing: throw new Exception(string) works?
In other words, it seems that the catch method is expecting a parameter of type Exception, but my Throw call sends a parameter of type string. How does this work?
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial