Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catch exception not of a type

Tags:

c#

Is there a difference when catching exceptions not of a type between :

try
{
    ...
}
catch (TaskCanceledException)
{
    throw;
}
catch (Exception exception)
{
    ...
}

and :

try
{
    ...
}
catch (Exception exception) when (!(exception is TaskCanceledException))
{
    ...
}
like image 596
Troopers Avatar asked May 02 '19 07:05

Troopers


People also ask

Which exceptions Cannot be caught?

When code reports an error, an exception cannot be caught if the thread has not yet entered a try-catch block. For example, syntaxError, because the syntax exception is reported in the syntax checking phase, the thread execution has not entered the try-catch code block, naturally cannot catch the exception.

Which catches any type of exception?

Catch block is used to catch all types of exception. The keyword “catch” is used to catch exceptions.

Does catch exception catch everything?

If you catch some Exception types and don't do anything with the information, you have no chance of knowing what went wrong in those situations, but if you catch all Exception subclasses you have no chance of knowing what went wrong in a much large number of situations.

Can you catch exception without try?

throws: The throws keyword is used for exception handling without try & catch block. It specifies the exceptions that a method can throw to the caller and does not handle itself.


1 Answers

Yes, there is.

In the second block of code you are filtering on general exception type. It is not meant to be filtered, what happens if "TaskCanceledException" is thrown? you are not handling it and it will escalate to enclosing code. You are not really meant to filter anything on "Exception" type since it is the parent for all other type of exception and it is the last point of handling exception. A better option would be to create a custom exception and put them in separate block of catch and filter on them if needed.

The first option is more correct compared to the second one. Though you should not be throwing any exception and stay away from them, unless it is a complete deal breaker. On top of that what is the point of putting a catch block with Exception type bellow TaskCanceledException catch block which throws exception? You are basically telling that "I Would like to handle all exception" when using catch with Exception type, but at the same time you through one exception in exceptional case. Either throw the original exception or handle them.

Hope this makes sense.

like image 82
vsarunov Avatar answered Oct 04 '22 21:10

vsarunov