I have there piece of code
//Code 1 Code 2 Code 3
try try try
{ { {
//Exp occur //Exp occur //Exp occur
} } }
catch (Exception e) catch (Exception) catch
{ { {
//Handle exp //Handle exp //Handle exp
} } }
What is the difference between all of three codes
P.S. I'm new to C#
and as far as Java
or Objective-C
is concerned this syntax throws error
'try-catch' is more time consuming than 'if-else'. 'if-else' communicate between the data provided to the program and the condition. 'try-catch' communicate between the data with the conditions and the system.
Answer: The “throws” keyword is used to declare the exception with the method signature. The throw keyword is used to explicitly throw the exception. The try-catch block is used to handle the exceptions thrown by others.
Try-catch block is used to handle the exception. In a try block, we write the code which may throw an exception and in catch block we write code to handle that exception. Throw keyword is used to explicitly throw an exception. Generally, throw keyword is used to throw user defined exceptions.
"Try" and "catch" are keywords that represent the handling of exceptions due to data or coding errors during program execution. A try block is the block of code in which exceptions occur. A catch block catches and handles try block exceptions.
Code 1
Its catching Exception in an object e
which can be later used for exception handling. For example you can log the Message property or view stack trace using e.Message
or e.StackTrace
Code 2
You are catching all the exception of the base type Exception
but since you don't have any object related to it, you can only throw that exception so that it can bubble up or you may ignore the exception. If in that code you had :
catch(InvalidCastException)
Then all the InvalidCastException
will be handled in the block without the exception object
Code 3
You are catching all type of exceptions irrespective of their type, which is similar to your code 2 with base class Exception
try-catch - MSDN
Although the catch clause can be used without arguments to catch any type of exception, this usage is not recommended. In general, you should only catch those exceptions that you know how to recover from.
Its always better if you catch specific exceptions before catching the base one. Something like.
try
{
}
catch(InvalidCastException ex)
{
}
catch(Exception ex)
{
}
try - catch - MSDN
It is possible to use more than one specific catch clause in the same try-catch statement. In this case, the order of the catch clauses is important because the catch clauses are examined in order. Catch the more specific exceptions before the less specific ones. The compiler produces an error if you order your catch blocks so that a later block can never be reached.
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