Catch block without arg - c#

I have a catch block like below:
catch (Exception e)
{
connection.Close();
return null;
}
I get a warning saying 'e' is not being used. I don't want to use it. But if I remove it I get an error saying "class type expected". What's to be done?

catch
{
connection.Close();
return null;
}

do this:
try
{
//code to throw exception
}
catch(ArgumentNullException)
{
//do something in response to this exception
}
catch(Exception)
{
//catch the general exception
}
this allows you to catch different types of exception without having to castch everything as with Danny's answer above (sorry i coulnd't just comment, not enough rating yet!)

Take the e out

Related

What is the advantage of using Exception filters and when should I use them?

Comparing the old way versus the new way of error handling, by using Exception filters, what is exactly the advantage for me of using filters and when should I use it? is there an scenario where I can get a good advantage of this new feature?
I have read about the unwinding stack but still I don't get the scenario where we can not handle that under the old way. Explain like I'm 5 please.
try
{
Foo.DoSomethingThatMightFail(null);
}
catch (MyException ex) when (ex.Code == 42)
{
Console.WriteLine("Error 42 occurred");
}
vs
try
{
Foo.DoSomethingThatMightFail(null);
}
catch (MyException ex)
{
if (ex.Code == 42)
Console.WriteLine("Error 42 occurred");
else
throw;
}
I know there is other version of this question, the problem is, that the question mention benefits that I cant actually find, for instance.
Exception filters are preferable to catching and rethrowing because
they leave the stack unharmed. If the exception later causes the stack
to be dumped, you can see where it originally came from, rather than
just the last place it was rethrown.
after doing some testing, I did not see the difference between both, I still see the exception from the place it was rethrown. So, or the information is not confirmed, I don't understand the Exception filters( that is why I am asking), or I am doing it wrong (also please correct me if I am wrong).
class specialException : Exception
{
public DateTime sentDateTime { get; } = DateTime.Now;
public int code { get; } = 0;
public string emailsToAlert { get; } = "email#domain.com";
}
then:
try
{
throw new specialException();
//throw new Exception("Weird exception");
//int a = Int32.Parse("fail");
}
catch (specialException e) when(e.code == 0)
{
WriteLine("E.code 0");
throw;
//throw e;
}
catch (FormatException e)
{
if (cond1)
{
WriteLine("cond1 " + e.GetBaseException().Message+" - "+e.StackTrace);
throw;
}
throw;
}
catch (Exception e) //when (cond2)
{
Console.WriteLine("cond2! " + e.Message);
throw;
}
I don't understand Paulo's answer. He may be correct or he may not be.
I definitely disagree with Alexander's answer. It is not just syntactic sugar. Pure syntactic sugar means it's solely an easier way of writing something, and that execution will be unchanged.
However, that's not the case in this situation. As Thomas Levesque points out in his blog, exception filters do not unwind the stack. So when debugging the program, if you have an exception thrown in your try block, with exception filters you'll be able to see what the state of the values are in the try block. If you weren't using exception filters, your code would enter the catch block and you would lose information about the state of the variables in the try block.
Note that I'm not talking about the stacktrace (it's a different but related concept to the stack). The stacktrace would be unchanged unless you explicitly did rethrow the exception as in throw exception; in a catch block where exception is the caught exception.
So while in some cases you can think of it as something that may or may not make your code cleaner (depending on your opinion of the syntax), it does change the behavior.
Exception filters have been added to C# because they were in Visual Basic and the "Roslyn" team found them useful when developing "Roslyn".
Beware that the filter runs in the context of the throw and not in the context of the catch.
Anyhow, one use might be something like this:
try
{
//...
}
catch (SqlException ex) when (ex.Number == 2)
{
// ...
}
catch (SqlException ex)
{
// ...
}
Edited:
One might think this is just syntactic sugar over this:
try
{
//...
}
catch (SqlException ex) when (ex.Number == 2)
{
// ...
}
catch (SqlException ex)
{
if (ex.Number == 2)
{
// ...
}
else
{
// ...
}
}
But if we change the code for this:
try
{
//...
}
catch (SqlException ex) when (ex.Number == 2)
{
// ...
}
It will be more like this:
try
{
//...
}
catch (SqlException ex) when (ex.Number == 2)
{
// ...
}
catch (SqlException ex)
{
if (ex.Number == 2)
{
// ...
}
else
{
throw
}
}
But there's one fundamental difference. The exception is not caught and rethrown if ex.Number is not 2. It's just not caught if ex.Number is not 2.
UPD: As pointed out in the answer by Paulo Morgado, the feature has been in CLR for quite some time and C# 6.0 only added syntax support for it. My understanding of it, however, remains as a syntactic sugar, e.g. the syntax that allows me to filter exceptions in a nicer way than it used to be, irrespective of how the previous "straightforward" method works under the hood.
=====
In my understanding, this is a syntactic sugar that allows you to more clearly define the block there your exception is going to be handled.
Consider the following code:
try
{
try
{
throw new ArgumentException() { Source = "One" };
throw new ArgumentException() { Source = "Two" };
throw new ArgumentException() { Source = "Three" };
}
catch (ArgumentException ex) when (ex.Source.StartsWith("One")) // local
{
Console.WriteLine("This error is handled locally");
}
catch (ArgumentException ex) when (ex.Source.StartsWith("Two")) // separate
{
Console.WriteLine("This error is handled locally");
}
}
catch (ArgumentException ex) // global all-catcher
{
Console.WriteLine("This error is handled globally");
}
Here you can clearly see that first and second exception are handled in the respective blocks that are separated using when safeguard, whereas the one global catch-all block will catch only the third exception. The syntax is clearer that catching all the exceptions in every block, something like:
catch (ArgumentException ex) // local
{
if (ex.Source.StartsWith("One"))
{
Console.WriteLine("This error is handled locally");
}
else
{
throw;
}
}

Code does not catch FormatException in C#

I have the following method in the class ProductServices:
public bool IsDownloadAllowed(int Id, string productId)
{
if (CustomStringFunctions.IsGuid(productId))
{
//Do Something
}
else
{
throw new FormatException("The Guid must be a valid Guid!");
}
}
If I use the method in the following set of instructions:
var _productServices = new ProductServices();
try
{
var flag = _productServices.IsDownloadAllowed(Id, productId);
//do something
}
catch (Exception e)
{
//handle exception
}
The exception is not caught by the catch statement. I also tried to replace Exception with FormatException with no luck. What am I doing wrong?
You must have mute exception in this code
if (CustomStringFunctions.IsGuid(productId))
{
//Do Something
}
You must be sure that you throw exception when occured (In the Do Something)
Sample of mute exception
Try
{
}
Catch(Exception ex)
{
//throw don't exist
}
Your code looks correct. A possible explanation for your problem is that CustomStringFunctions.IsGuid is incorrectly returning true, so the \\do something branch is executing instead of the exception-throwing branch.

Catch two exceptions in the same catch block?

I have a method that can throw two different exceptions, CommuncationException and SystemException. In both cases I do the same three-line code block.
try {
...
}
catch (CommunicationException ce) {
...
}
catch {SystemExcetion se) {
...
}
Is there any possibility to do it like that?
try {
...
}
catch (CommunicationException ce, SystemException se) {
...
}
Then I would not have to write this much code. I know I could extract the exception handling to a private method, but since the code is only 3 lines long, the method definition would take more code than the body itself.
If you can upgrade your application to C# 6 you are lucky. The new C# version has implemented Exception filters. So you can write this:
catch (Exception ex) when (ex is CommunicationException || ex is SystemException) {
//handle it
}
Some people think this code is the same as
catch (Exception ex) {
if (ex is CommunicationException || ex is SystemException) {
//handle it
}
throw;
}
But it´s not. Actually this is the only new feature in C# 6 that is not possible to emulate in prior versions. First, a re-throw means more overhead than skipping the catch. Second, it is not semantically equivalent. The new feature preserves the stack intact when you are debugging your code. Without this feature the crash dump is less useful or even useless.
See a discussion about this on CodePlex. And an example showing the difference.
In fact, you could catch only SystemException and it would handle CommunicationException too, because CommunicationException is derived from SystemException
catch (SystemException se) {
... //this handles both exceptions
}
Unfortunately, there is no way. The syntax you used is invalid and a fall through like in a switch-statement isn't possible either. I think you need to go with the private method.
A little hacky work-around would be something like this:
var exceptionHandler = new Action<Exception>(e => { /* your three lines */ });
try
{
// code that throws
}
catch(CommuncationException ex)
{
exceptionHandler(ex);
}
catch(SystemException ex)
{
exceptionHandler(ex);
}
You need to decide for yourself if this makes any sense.
No, you can't do it that way. The only way i know of is to catch a generic Exception and then check what type it is:
try
{
...
}
catch(Exception ex)
{
if(ex is CommunicationException || ex is SystemException)
{
...
}
else
{
... // throw; if you don't want to handle it
}
}
What about
try {
...
}
catch (CommunicationException ce) {
HandleMyError(ce);
}
catch {SystemExcetion se) {
HandleMyError(se);
}
private void HandleMyError(Exception ex)
{
// handle your error
}
Possible Duplicate of
Catch multiple exceptions at once?
I quote the answer here:
catch (Exception ex)
{
if (ex is FormatException ||
ex is OverflowException)
{
WebId = Guid.Empty;
return;
}
else
{
throw;
}
}
Dragging this one up from the depths of history as it happened to pop up in some search results.
With the advent of C# 7.0 (which arrived in 2017 with VS2017, .net framework 4.7 and dotnet core 2.0) you can now do things like this:
try {
...
}
catch (Exception e) when (e is CommunicationException || e is SystemException) {
...
}
Since you're doing the same for both type of exceptions, you could just go:
try
{
//do stuff
}
catch(Exception ex)
{
//normal exception handling here
}
Only catch explicit Exception types if you need to do something unique for it.

Which exception does SMO Transfer Raise?

While using this code
try
{
transfer.TransferData();
}
catch (SmoException smoex)
{
//Do something
}
catch (Exception ex)
{
//Do something else
}
The exception is always caught by the second catch statement.
Does someone know why this happens?
Thanks in Advance
Use this to determine what the exception you get actually is:
try
{
transfer.TransferData();
}
catch (Exception ex)
{
var theRealExceptionTypeName = ex.GetType().Name;
}
This happens because the exception is not an SmoException.
It is either an Exception or another exception type deriving from Exception, but not SmoException. SmoException would be caught by the first handler if it were truely an SmoException or a class deriving from SmoException. Hopefully that sentence isn't as confusing to read as it was to type!
Further reading on exceptions and exception handling:
http://msdn.microsoft.com/en-us/library/ms173160(v=vs.80).aspx
Documentation doesn't say what exceptions are thrown:
http://msdn.microsoft.com/en-us/library/microsoft.sqlserver.management.smo.transfer.transferdata.aspx

Exception from within a finally block

Consider the following code where LockDevice() could possibly fail and throw an exception on ist own. What happens in C# if an exception is raised from within a finally block?
UnlockDevice();
try
{
DoSomethingWithDevice();
}
finally
{
LockDevice(); // can fail with an exception
}
Exactly the same thing that would happen if it wasn't in a finally block - an exception could propagate from that point. If you need to, you can try/catch from within the finally:
try
{
DoSomethingWithDevice();
}
finally
{
try
{
LockDevice();
}
catch (...)
{
...
}
}
The method is called Try / Catch
Where is your catch?
UnlockDevice();
try
{
DoSomethingWithDevice();
}
catch(Exception ex)
{
// Do something with the error on DoSomethingWithDevice()
}
finally
{
try
{
LockDevice(); // can fail with an exception
}
catch (Exception ex)
{
// Do something with the error on LockDevice()
}
}

Categories

Resources