I have something like this:
public byte[] AnyMethod(){
try {
...
}
catch (Exception e) {
string errorMessage =
"Some custom message, which should the caller of that method should receive";
// I thought something of this ,to pass through my custom exception to the caller?!
throw new ApplicationException(errorMessage);
//but this does not allow the method
}
}
But this:
throw new ApplicationException(errorMessage);
Will result in:
An exception of type 'System.ApplicationException' occurred in ...dll but was not handled in user code
How to do give the custom errror message to the caller of my above mentioned method ?
First, use a custom exception or at least one more meaningful instead of ApplicationException
. Second, you have to catch the exception if your method throws it.
So the calling method should also wrap the method call in a try...catch
:
try
{
byte[] result = AnyMethod();
}catch(MyCustomException ex)
{
// here you can access all properties of this exception, you could also add new properties
Console.WriteLine(ex.Message);
}
catch(Exception otherEx)
{
// all other exceptions, do something useful like logging here
throw; // better than throw otherEx since it keeps the original stacktrace
}
Here's an abstract, simplified example:
public class MyCustomException : Exception
{
public MyCustomException(string msg) : base(msg)
{
}
}
public byte[] AnyMethod()
{
try
{
return GetBytes(); // exception possible
}
catch (Exception e)
{
string errorMessage = "Some custom message, which should the caller of that method should receive";
throw new MyCustomException(errorMessage);
}
}
But note that you should not use exceptions for normal program flow. Instead you could either return true
or false
to indicate if the action was successful or use an out
parameter for the byte[]
like int.TryParse
(or the other TryParse
methods).
publy byte[] AnyMethod(){
try{
}catch(Exception e){
string errorMessage = string.Format("Some custom message, which should the caller of that method should receive. {0}", e);
//I thought something of this ,to pass through my custom exception to the caller?!
throw new ApplicationException(errorMessage);
//but this does not allow the method
}
}
OR
public byte[] AnyMethod(){
try{
}catch(Exception e){
string errorMessage = "Some custom message, which should the caller of that method should receive";
//I thought something of this ,to pass through my custom exception to the caller?!
throw new ApplicationException(errorMessage, e);
//but this does not allow the method
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.