Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is an empty try/catch equal to catching Exception?

Tags:

c#

.net

try { } catch (Exception) { } 

can i just write

try { } catch { } 

Is this ok in C# .NET 3.5. Code looks nicer but I don't know if is the same.

like image 241
senzacionale Avatar asked Aug 02 '10 21:08

senzacionale


People also ask

What happens if catch block is empty?

It will generate an exception that is caught by the catch block. The catch block catches and handles the exception. If the catch block is empty then we will have no idea what went wrong within our code.

What happens if try block is empty in Java?

try block will work fine if nothing is in it . You cannot use any checked exception in a catch block if it is never thrown. so with the empty try block u can use catch with unchecked exceptions if exception is thrown or not but u can use checked exception only if it is thrown.

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.

Should a try always have a catch?

There is no compile time error because a try block does not have to be followed by a catch. It's semantically correct, and often necessary to just want a finally block after a try. Perhaps the exception is being thrown from the method but you still want to close a connection.


1 Answers

They are not the same.

catch (Exception) { } will catch managed exceptions only; catch { } will catch non-CLS exceptions as well: http://msdn.microsoft.com/en-gb/bb264489.aspx

An unhandled non-CLS compliant exception becomes a security issue when previously allowed permissions are removed in the catch block. Because non-CLS compliant exceptions are not caught, a malicious method that throws a non-CLS compliant exception could run with elevated permissions.

Edit: Turns out .NET 2.0+ wraps the values -- so they are the same. That's a bit of a relief!

like image 51
Rei Miyasaka Avatar answered Sep 28 '22 10:09

Rei Miyasaka