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.
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.
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.
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.
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.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With