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.Mes sage);
...
}
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.
catch (Exception ex)
{
...
ImportStatus.Append(ex.Mes
...
}
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);
ASKER
Right, but what if I say the following in the try block:
throw new Exception("Address length is too long");
Will this be caught by the catch block?
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
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
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?
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?
ASKER
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
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
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.