The variable 'MyException' is declared but never used in the instance [duplicate] - c#

This question already has answers here:
The variable 'MyException' is declared but never used
(6 answers)
Closed 6 years ago.
I need to clear this warning :
try
{
// doSomething();
}
catch (AmbiguousMatchException MyException)
{
// doSomethingElse();
}
The compiler is telling me : The variable 'My Exception' is declared but never used
How can I fix this.

Try this one,
try
{
doSomething()
}
catch (AmbiguousMatchException)
{
doSomethingElse()
}

If you are not going to use the exception details, you can use the try like this:
try
{
doSomething();
}
catch // all types of exceptions will caught here
// if you need to deal with particular type of exceptions then specify them like
// catch (AmbiguousMatchException)
{
doSomethingElse();
}
Or else you have to use the variable for something like the following:
try
{
doSomething();
}
catch (AmbiguousMatchException MyException)
{
WriteToLog(MyException.ToString());
// doSomethingElse();
}
where WriteToLog method will be defined as like the following:
public static void WriteToLog(string exceptionDetails) {
// write the details to a file/DB
}

Related

How to override Catch(Exception) in Parent (Caller) method?

Is there any way to force that the caller could override the catch ?
i.e.
void ParentMethod()
{
try
{
child_method();
}
catch(Exception e)
{
MessageBox.Show("parent");
}
}
void child_method()
{
try
{
smth();
}
catch(Exception e)
{
MessageBox.Show("child");
}
}
so, when smth throws exception, instead of "child", i could override that catch with parent, and show i.e. parent.
Note 1: I am in a case, where I don't control child. However, for the sake of the answer completion, you can still answer for the case when child is controlled.
Note 2: I nowhere mentioned that I have classes or inheritance. Please avoid answers for virtual/override things. I know that.
If the child method's code is also owned/controlled/has access to, by the person/group who owns/controls the code for parent method, then you can do few things -
if there's always a parent method to call this child method and that, child method is not going to be on its own (by your design), you can ignore the try-catch in child and have the parent handle whatever they want to.
If (not #1) then its true from the above comment.
Ideally, and this is purely from my experience and opinion, if a method needs try-catch (based on what it does would qualify for it), catch block should catch the exception, do something like log it, and throw unless thats the last calling method.
There's not a way to enforce that a called method must rethrow any raised exceptions. The calling method is free to swallow whatever exception it wants.
That said, the way to catch the exception in the parent method also is to either rethrow the original exception or a new exception:
void child_method()
{
try
{
smth();
}
catch(Exception e)
{
MessageBox.Show("child");
//or: throw new Exception("Exception thrown in child");
}
}
Short answer is no.
But there I guess you misunderstood few things about Object Oriented Programming.
So you can override a method with another method with same name and different prototype if you want more configuration or different behaviour.
You can inherite from a class and override methods to share a common part and adjust whatever you want.
Ok so there you want a common part parent that would contain the try catch section.
So there you got a really different approach from what you did, but if I understood well quite suite what you want.
using System;
namespace ConsoleApp4
{
class Program
{
static void Main(string[] args)
{
VirtualTest test1 = new Test1();
test1.ParentMethod();
VirtualTest test2 = new Test1();
test2.ParentMethod();
Console.ReadKey();
}
}
abstract class VirtualTest
{
public void ParentMethod()
{
try
{
ChildMethod();
}
catch
{
Console.WriteLine("parent");
}
}
protected abstract void ChildMethod();
}
class Test1 : VirtualTest
{
protected override void ChildMethod()
{
try
{
throw new ArgumentException("A message");
}
catch (ArgumentException e)
{
Console.WriteLine(e.Message);
throw; //Here is a way to handle more specificly some
//errors but still throwing and keeping the original stacktrace
}
}
}
class Test2 : VirtualTest
{
protected override void ChildMethod()
{
throw new NotImplementedException();
}
}
}
In that case you also have more control of what you're catching at which level and you can decide wether you want to deal with it or not.
The finer level you handle the Exception the better.
Also in that example Parents are actually parents and Children are actually childrend in a POO way.

Defining and catching new custom exception of custom type

I have the following exception that I created for my testing scenarios:
class EvaluationException : Exception
{
public PrettyError ExceptionDetails { get; }
public EvaluationException(PrettyError exceptionDetails)
{
this.ExceptionDetails = exceptionDetails;
}
}
And I'd like to use the following catch block
catch (Exception e)
{
if(e is EvaluationException)
{
e.ExceptionDetails //do stuff;
}
}
However e.ExceptionDetails does not contain a definition for ExceptionDetails. I've tried casting a la (EvaluationException)e and e = e as EvaluationException and I still cannot access the new class attribute that I declared for my custom exception.
How can I do this?
Specific Problem
e is still the wrong type. When you do this:
if(e is EvaluationException)
{
e.ExceptionDetails //do stuff;
}
You're not actually modifying the type of e. It's still an Exception, which indeed doesn't have that property. In order to access that property, you need to interpret e as that type when reading it:
if(e is EvaluationException)
{
(e as EvaluationException).ExceptionDetails //do stuff;
}
or perhaps:
if(e is EvaluationException)
{
var ex = e as EvaluationException;
ex.ExceptionDetails //do stuff;
}
Taking a Step Back
Though, since this is in a catch block, you may make better use of the tooling (and end up with better organized code) to separate your exception handlers by type:
try
{
//...
}
catch (EvaluationException e)
{
// specific handling for this exception type
}
catch (Exception e)
{
// catch-all for non-specific exceptions
}
You can chain as many of those as you like. This allows the runtime to determine which catch block to use, so your code can focus on handling the exception instead of cluttering itself up with trying to determine the exception.
The casting does not work because e is already of type Exception. If you assign to a new variable it would work.
You can also catch specific exception types to make yor life easier like:
catch (EvaluationException evalex)
{
//do stuff
}
catch (Exception ex)
{
// do other stuff
}

C# won't catch "nested" custom exception [duplicate]

This question already has answers here:
What is the best way to catch exception in Task?
(2 answers)
Catching Error when using Task.Factory
(5 answers)
Closed 5 years ago.
I'm trying to catch a "nested" or "encapsulated" custom error (I504Error) in my code. I know this normally isn't best practice, but it should work for my use case as the error is very specific. I'm trying to get the try/catch block to catch the I504Error in my Main method but it doesn't catch it, even though it's getting called from inside the try/catch block. My program just stops where I'm throwing the error. What am I doing wrong here?
// Custom Error Handler
public class I504Error : Exception
{
public I504Error()
{
}
}
// Classes
public abstract class AbstractIternetThing
{
public abstract void DoSomething();
}
public class IternetThing : AbstractIternetThing
{
public override void DoSomething()
{
// bunch of other stuff
if (iternetThingWorkedProperly == false)
{
// Program stops here, doesn't get caught by the try/catch block in Program.Main()
throw new I504Error();
}
}
}
// Main script
class Pogram
{
static void Main(string[] args)
{
List<Task<AbstractIternetThing>> programThreads = new List<Task<AbstractIternetThing>>();
IternetThing iThing = new IternetThing();
try
{
for (int wantedThread = 0; wantedThread < 5; wantedThread++)
{
Task<AbstractIternetThing> iThingTask = new Task<AbstractIternetThing>(() => iThing.DoSomething());
iThingTask.Start();
}
}
// The Error should get caught here, but it doesnt?
catch (I504Error)
{
// Do something else
}
}
}
It is because you have it in a Task which is on a separate asynchronous execution path. Consider using async-await. Then the compiler will rewrite your code to make it work as you expect.

Attribute to suppress certain types of exceptions?

Is there any attribute that I can use, attached to the method definition, that will suppress any exceptions of a certain type originating in that method? e.g.
[SuppressException(typeof(TimeoutException))]
public void TroubleMethod()
{
}
So when there is a TimeoutException, it won't throw outside of TroubleMethod?
You can use exception handling around the entire method:
public void TroubleMethod()
{
try {
// ...
} catch(TimeoutException) {
// Throw away
}
}
I don't think an attribute that does what you describe exists, though. If you want the debugger to step through your method, you can always use [System.Diagnostics.DebuggerStepThrough()], but as for suppressing exceptions, I don't think that's possible.
You can use PostSharp to do some tricky instrumentation to add such attribute.
If you really want to do this, you can get a bit closer to your attribute-like syntax with:
static void SuppressException<TException>(Action a) where TException : Exception
{
try
{
a();
}
catch (TException) { }
}
public void TroubleMethod()
{
SuppressException<TimeoutException>(() => {
...
}
}
Not that I am aware of, but you can always do this:
public void TroubleMethod()
{
try
{
// silly code goes here
}
catch() { }
}
A bad idea in almost all circumstances, though sometimes acceptable (rare). Just make sure to leave a comment for future maintainers (this includes you).
you could use try-catch to catch the exeptions and just ignore it or better you could respond to that exeption
check out the reference

What is the best way to re-use exception handling logic in C#?

I have two functions that have different enough logic but pretty much the same exception handling:
public void DoIt1 // DoIt2 has different logic but same exception handling
{
try
... DoIt1 logic
catch (MySpecialException myEx)
{
Debug.WriteLine(myEx.MyErrorString);
throw;
}
catch (Exception e)
{
Debug.WriteLine(e.ToString());
throw;
}
}
It is not possible to use a single entry point for DoIt1 and DoIt2, because they are called in from outside.
Is Copy/Pase (for the exception block) the best approach?
It depends... if there is that much commonality, you could pass in the thing to do as a parameter - either as an interface or a delegate:
void Foo(Action thingToDo) {
if(thingToDo == null) throw new ArgumentNullException("thingToDo");
try {
thingToDo();
} catch {...} // lots of
}
And call as:
Foo(delegate { /* logic A */ });
Foo(delegate { /* logic B */ });
Try:
public static class Catching<TException> where TException : Exception
{
public static bool Try<T>(Func<T> func, out T result)
{
try
{
result = func();
return true;
}
catch (TException x)
{
// log exception message (with call stacks
// and all InnerExceptions)
}
result = default(T);
return false;
}
public static T Try<T>(Func<T> func, T defaultValue)
{
T result;
if (Try(func, out result))
return result;
return defaultValue;
}
}
Example:
int queueSize = Catching<MyParsingException>
.Try(() => Parse(optionStr, "QueueSize"), 5);
If Parse throws a MyParsingException, queueSize will default to 5, otherwise the returned value from Parse is used (or any other exception will propagate normally, which is usually what you want with an unexpected exception).
This helps to avoid breaking up the flow of the code, and also centralises your logging policy.
You can write specialised versions of this kind of exception wrapping for special cases, e.g. catching a particular set of three exceptions, or whatever.
For the extreme end of the spectrum of possible solutions, check out Aspect-Oriented-Programming techniques, and tools such as PostSharp or Microsoft Policy Injection Block. This way you can define an aspect that does something on exception and weave it into all places in your code that need it.
If you just want to log the exceptions' messages and items, without doing special processing in the catch block, you could create a Reflection-based Object logger, passing the Exception as an argument. Doing so, you don't have a lot of catch blocks.
And if you are the code's owner, you can put the logging procedure inside the MySpecialException's constructor, removing the catch's block and making the code cleaner.
You could have something like:
public static class ErrorHandler
{
public static void HandleMyException(MyException myEx)
{
Debug.WriteLine(myEx.MyErrorString);
throw;
}
public static void HandleException(Exception myEx)
{
Debug.WriteLine(e.ToString());
throw;
}
}
or, in this specific case, have a more generic function like:
public static class ErrorHandler
{
public static void WriteAndThrow(string msg)
{
Debug.WriteLine(msg);
throw;
}
}

Categories

Resources