I want to write some try and catch that catch any type or exception, is this code is enough (that's the way to do in Java)?
try { code.... } catch (Exception ex){}
Or should it be
try { code.... } catch {}
?
C itself doesn't support exceptions but you can simulate them to a degree with setjmp and longjmp calls.
Handle Multiple Exceptions in a catch Block In Java SE 7 and later, we can now catch more than one type of exception in a single catch block. Each exception type that can be handled by the catch block is separated using a vertical bar or pipe | .
In C#, You can use more than one catch block with the try block. Generally, multiple catch block is used to handle different types of exceptions means each catch block is used to handle different type of exception.
2) There is a special catch block called the 'catch all' block, written as catch(…), that can be used to catch all types of exceptions. For example, in the following program, an int is thrown as an exception, but there is no catch block for int, so the catch(…) block will be executed.
Both approaches will catch all exceptions. There is no significant difference between your two code examples except that the first will generate a compiler warning because ex
is declared but not used.
But note that some exceptions are special and will be rethrown automatically.
ThreadAbortException
is a special exception that can be caught, but it will automatically be raised again at the end of the catch block.
http://msdn.microsoft.com/en-us/library/system.threading.threadabortexception.aspx
As mentioned in the comments, it is usually a very bad idea to catch and ignore all exceptions. Usually you want to do one of the following instead:
Catch and ignore a specific exception that you know is not fatal.
catch (SomeSpecificException) { // Ignore this exception. }
Catch and log all exceptions.
catch (Exception e) { // Something unexpected went wrong. Log(e); // Maybe it is also necessary to terminate / restart the application. }
Catch all exceptions, do some cleanup, then rethrow the exception.
catch { SomeCleanUp(); throw; }
Note that in the last case the exception is rethrown using throw;
and not throw ex;
.
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