Trick Exception Treatment

What is the difference between using

catch(Exception ex)
{
   ...
   throw ex;
}

and using

catch   //  might include  (Exception) 
{
   ...
   throw;
}
+3
source share
5 answers

throw exRe-throws the exception object from this point. This is usually bad because it destroys the useful information of the call stack, which leads to the original problem.

throwreleases the original caught exception from the point at which it was actually thrown. It saves the call stack information to this point, and not to the point you caught.

catch(Exception) catch - , , , , , , - , - . . catch(SomeKindOfException), ( , ). , :

try
{
    //some file operation
}
catch(FileNotFoundException fnfex)
{
    //file not found - we know how to handle this
}
//any other kind of exception,
//which we did not expect and can't know how to handle,
//will not be caught and throw normally
+12

catch 1.x . 2 (IIRC) Exception, .

, catch. , throw; , .

throw ex; catch , , , . , , , , .

, . , :

catch (Exception ex) {
   ...
   throw;
}

:

catch (Exception ex) {
   ...
   throw new ApplicationException("Ooops!", ex);
}

, Exception, , . , , , .

+4

, . .

, "catch" , , .

- "catch (object)".

+1

0

As far as I know, this is the same (using Exception .. because all exceptions come from this class). It becomes different when you catch only the child of the Exception ... or when you have several "catch" catching different children. It may also be that you catch Exception, modify the message, and discard it.

-1
source

Source: https://habr.com/ru/post/1721597/


All Articles