debugcsharpModerate
Compiler warning on unused exception...need to improve structure?
Viewed 0 times
exceptionneedunusedimprovestructurecompilerwarning
Problem
Consider the below:
Obviously I have abstracted quite a bit for the example, but the idea is that the try block performs a task which can cause one of two types of runtime exception.
In the event that the exception type is
I do not have access to the
This all looks fine to me, and works fine, but I get a compiler warning because
I can think of a couple of hacky ways like
public int DoSomethingComplicated(ComplicatedObject input)
{
try {
return input.Analyse();
}
catch(CustomExceptionOne ex1)
{
throw;
}
catch(CustomExceptionTwo ex2)
{
Log(ex2.Message);
return -1;
}
}Obviously I have abstracted quite a bit for the example, but the idea is that the try block performs a task which can cause one of two types of runtime exception.
In the event that the exception type is
CustomExceptionOne, I want to simply throw the exception. For CustomExceptionTwo on the other hand, I want to log the issue but return -1.I do not have access to the
input.Analyse() method in order to change it.This all looks fine to me, and works fine, but I get a compiler warning because
ex1 is technically never used. I don't really want to throw the entire ex1 exception, so I am wondering how I can get this warning to go away.I can think of a couple of hacky ways like
Console.WriteLine(ex1.Message) or something but that isn't a route I particularly want to go down.Solution
You can refactor your code the following way:
Alternatively, you can use
public int DoSomethingComplicated(ComplicatedObject input)
{
try
{
return input.Analyse();
}
catch(CustomExceptionTwo ex2)
{
Log(ex2.Message);
return -1;
}
}throw; re-throws the same exception, so there is no point in such catch block. Alternatively, you can use
catch(CustomExceptionOne) syntax.Code Snippets
public int DoSomethingComplicated(ComplicatedObject input)
{
try
{
return input.Analyse();
}
catch(CustomExceptionTwo ex2)
{
Log(ex2.Message);
return -1;
}
}Context
StackExchange Code Review Q#32418, answer score: 10
Revisions (0)
No revisions yet.