Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to disable CS0168 warning about unused exception variable in catch block?

I always add a variable in my catch structure:

catch (Exception e)
{
    // ...
}

Even when I don't use e in the catch block. I do so because I don't know how to get the exception (and its detail) if I enter an "anonymous" catch while debugging.

catch { /* ...how to get the exception from here ?... */ }

If the exception is not used in the catch block I get a CS0168 warning: "variable e is unused"

I know how to globally disable CS0168 (or locally) but I'd rather not have to do so because it could hide useful messages too.

I'd rather not have to add fake code in the block to use the exception so that it does not raise the warning.

I'd rather not edit/remove the parameter accordingly to its (not) usage in the catch block just to remove the warning.

Ideally I want to know how to get the instance of the exception when debugging.

like image 376
frenchone Avatar asked Dec 03 '22 21:12

frenchone


2 Answers

If you just want to get the instance of the exception in the debugger while you are
in a catch { ... } block, you can use a pseudovariable.

Just open the Watch window and add $exception.

You can use this pseudovariable in any type of catch block to get the instance of the exception.

like image 151
haindl Avatar answered May 25 '23 01:05

haindl


You can you #pragma Directive, this will disable the warning message. and you can restore it back too(like in the below code), which is advisable.

#pragma warning disable CS0168 // The variable 'e' is declared but never used
catch (Exception e)
#pragma warning restore CS0168 // The variable 'e' is declared but never used
{
    // ...
}
like image 29
Siddharth Dinesh Avatar answered May 25 '23 01:05

Siddharth Dinesh