How does Catch (object o) work? - c#

I was reading the blog of Chris Brumme and this code was listed:
catch (object o) { .... }
There wasn't a full explanation on this line although the article I read was on general exception handling (SEH and exceptions in managed code).
How does that line above work? Exceptions are always of type Exception (or derived)? To catch ALL exceptions just omit the brackets and its contents or catch (Exception x) will do.
Thanks

That shouldn't be legal:
15.10 The try statement
When a catch clause specifies a class-type, the type shall be System.Exception or a type that derives from System.Exception.
Similarly, the only thing that C# lets you throw is an object of type System.Exception.
However,
Note: Some environments, especially those supporting multiple languages, might support exceptions that are not representable as an object derived from System.Exception, although such an exception could never be generated by C# code. In such an environment, a general catch clause might be used to catch such an exception....
The general catch clause doesn't let you catch the object, though. If you're only using C#, then I would use catch (Exception e) if I wanted to take some action on the exception's message, or log it somewhere; I would save catch for when you really don't care about the actual exception value. If you were actually depending on the general catch clause to catch things that aren't Exceptions, you should document it with a comment.

From framework 2.0 catching an Object is pointless.
Earlier you could get an exception from unmanaged code that did not derive from the Exception class, but from framework 2.0 all unmanaged exceptions are wrapped in an object derived from Exception, thus there is no longer any use for catch (Object o) or a parameterless catch.

First of all, in most languages Exception dervies from Object.
Also, depending on the language, you may throw anything; not just an object that derives from Exception.
This would allow you to catch these as well.

Exception inherits from Object.
Thus, the line will "work" (in that it catches all exceptions), but it's still not good style.
In fact, catching all exceptions regardless of type is usually a bad idea anyway.

Exception is a Object and it can be derived, BUT the catch object must be an Exception and expression are not permitted (so or an Execption or is a derived of Exception)
When the Exception is cathed it will execute the code inside the catch and just in this scope your exception object will be defined.
If u dont put code, nothing will append.
!Note if put a derived type the catch will work just if the trhow execption has got this type
example
//BLOCK ANYTHING
try
{
...do something..
}
catch
{
}
//OR
try
{
...do something..
}
catch(Exception ex)
{
...do something else..
}
<---- Here the variable ex is not defined
for custom blocking:
class MyException : Exception
{
...bla bla...
}
class OtherEx: notImplementedException
{
...foo foo..
}
try
{
}
catch(MyException ex)
{
Console.WriteLine("Is mine !");
}
catch(OtherEx ex)
{
Console.WriteLine("Is other !");
}
catch(Exeception ex)
{
Console.WriteLine("Is anything else !");
}

Related

how to throw an exception that is not catched as an exception

Simple, I have catch(Exception e) everywhere in my code.
However, I would like to have a type which wouldn't be caught by this catch..
I looked up all the types and try most of them and they seem to all be caught... SystemException, etc.
How could I throw an error that skip this catch?
In C# 6.0 you can define exception filters which would allow you to do what you want, although if you are needing to do this, you probably need to address the real source of the issue.
try
{
...
}
catch (Exception ex) if (ex.GetType() != typeof(YourExceptionToIgnore))
{
...
}
FYI, catching an exception of type Exception is advised against in the framework guidelines - as mentioned elsewhere in this post, you should be only catching the specific exception types you expect to be raised.
You can't. However, you can code in such a way that the catch block does nothing or you can place things that have to happen into the finally block
I would like to have a type which wouldn't be caught by this catch
Catch the more specific "type" you want before the catch(Exception e). That way, you could specifically handle the more specific "type" of Exception
As others suggesting you should only catch specific type exception as recommended practice. Though you can use exception filters which are available in latest version of C# 6.
try
{
// Some exception
}
catch (Exception e) if (e.Getype() != typeof(YourCustomException))
{
// handle exception except of type YourCustomException
}
You could try an empty catch, or a switch-case within your catch.

Difference between parameterless catch and other catch

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
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.
Code 1 - fairly normal catch, hopefully doesn't need explanation
Code 2 - You want to execute a particular piece of code when a particular exception occurs, but you have no intention of actually interacting with the exception object. Should almost always have a throw; statement at the end, so that someone else higher up the stack who does care can catch it.
Code 3 - You want the code to execute for any exception(*) (except for any caught by earlier catch clauses of the same try). Again, should almost always include a throw; so that higher code can catch and actually process the exception.
At some level (possibly just at the top level, in the unhandled exception handlers for whatever environment you're in), something ought to be inspecting the exception object and probably logging it (if possible).
Here if you want to use the variable 'e' for getting the Exception message, Line or type.
//Code 1
try
{
//Exp occur
}
catch (Exception e)
{
//Handle exp
}
Below code for getting particular type of Exception and not dealing with Exception variable.
//Code 2
try
{
//Exp occur
}
catch (Exception)
{
//Handle exp
}
Below code catching all types of exceptions.
//Code 3
try
{
//Exp occur
}
catch
{
//Handle exp
}
if you plan to actually use the exception object, to log its properties to a log file or to show a message box or to throw another kind of exception and pass the current exception to its constructor, then you must use the first of the three (most left one).
in general the most used approach is the first one anyway, if you want to handle different kind of exceptions separately you can have multiple catch blocks starting with the most specialized on top and have the one you wrote at the bottom so that all exceptions not already handled will end in the generic catch block.
Nothing. They all catch EVERY exception that could possibly occur (by catching base type Exception or just any). This is typically frowned upon, for good reason. You should catch specific exceptions in the order you expect, and then if you do want to catch all exceptions catch Exception at the end.
try
{
}
catch (MyCustomException)
{
// do something for your custom exception
}
catch (Exception)
{
// do something for everything else
}
When you specify a variable for your exception such as catch (Exception e) you will have access to the stack trace (and other exception information) via e.Property or simply e.ToString() for the full message. It's also best practice to throw the exception when caught (well, unless you want to suppress it at this level and not allow your calling code to see the exception) so it bubbles up and you preserve the stack trace:
catch (Exception e)
{
// do something with e
throw;
}
Code 1 catches every exception (in your case!) and declares it, so you can use it later e.g. for Error-Messages.
MessageBox.Show(e.Message);
Code 2 also catches every exception (in your case!), but you can't use it, because it is not declared.
These two methods are not designed for that, they're designed to catch specific or custom exceptions.
try
{
//mycode
}catch(MyException myExc)
{
//TODO HERE
Console.Write(myExc.Message);
}
The third one catches all exceptions. Because there is no definition.
Take a look at: http://msdn.microsoft.com/de-de/library/0yd65esw%28v=vs.80%29.aspx
to learn more about exceptions in C#.
Differences:
Declaring Exception Parameter ex allows you to access the Exception object, in order to see and work with its properties, fields, methods and the like. This "ex" variable works like any parameter in any method.
Declaring Exception Type without parameter ex allows you to separate several "catch" areas for different types of exception. It is useless, and functionally equivalent to code sample 3 as you define it here, but if you need to do different actions depending on the type of the exception, and you do not need to access the exception object (you only need to know the type of the exception), then this is your way to go.
Untyped Catch Exception Handler allows you to add a fallback for any Exception that might be thrown, whatever its type. Since it is not parameterized, however, you won't have access to the Exception object's properties or methods. Both code sample 2 and code sample 3 therefore are equivalent.
Example:
try{ // code that throws exception }
catch(TypeException ex)
{
// code to handle exceptions of type TypeException
// I can access ex parameter, for example to show its Message property
MessageBox.Show(ex.Message);
}
catch(OtherTypeException)
{
// code to handle exceptions of type OtherTypeException
// I cannot access the ex parameter since it is not declared, but I know
// the exact type of the exception
MessageBox.Show("There was an exception of Other Type");
}
catch
{
// code to handle any other exception
// this is functionally equivalent to catch(Exception) since all typed exceptions
// inherit from the base type Exception
MessageBox.Show("An unknown exception has been thrown.");
}
...

Reading exception from try catch when exception type not specified

In cases when you use a try catch block as such.
try {
//Do my work!
}
catch
{
//Handle my exception
}
Is there some way to refer to the exception object in the catch block?
ie:
try {
//Do my work!
}
catch
{
//Handle my exception
MyUndefinedExceptionObject.Message ????
}
EDIT: I don't think I was clear
enough. I am aware of how one would
typically catch exceptions using a try
catch block. What I am wondering is
given you have the ability to not
specify a type for your exception yet
declare the block is there still some
way of retrieving the exception object
in such cases? Judging by your answers
however I assume there isn't?
You'll want to catch the exception type you care about. When you do, you'll have access to all the properties of that exception.
try
{
//Do my work!
}
catch (MyExceptionType e)
{
string s = e.Message;
}
Here's a reference in MSDN, to get up to speed.
Regarding your edit: no there is no way to access the thrown exception unless the exception is explicitly specified in your catch statement.
Yes, like this:
try
{
//Do my work!
}
catch (mySpecificException myEx)
{
//Handle my exception
}
catch (Exception ex)
{
//Handle my exception
}
(Most specific to least specific)
No.
Using the bare catch indicates that you do not care about the actual exception otherwise, why not use
catch (System.Exception ex)
to catch any exception? Of course, you should only catch exceptions you will handle.
You need to indicate the specific type of exception that you are catching, and assign that to a variable.
Do that using this syntax instead:
try
{
// Do work
}
catch (MyUndefinedExceptionObject ex)
{
Debug.WriteLine(ex.Message);
}
You can also include multiple catch blocks with the type of exception altered accordingly. However, remember that you should always order them from most derived to least derived, ending with the base class for all exceptions, System.Exception.
You also should generally refrain from catching System.Exception, instead preferring only to catch the derived exceptions that you can handle in the catch block and that won't corrupt your program's state. Catching System.Exception class is a bad idea because you'll also catch exceptions that you won't be able to handle, like an OutOfMemoryException or a StackOverflowException.
Microsoft has a helpful article on best practices here: Best Practices for Handling Exceptions

Exception catching

What is the difference between
try
{
...
}
catch (NHibernate.ADOException exception)
{}
and
try
{
...
}
catch (exception ex)
{}
In the catch block you specify which exceptions you wish to catch. So if you have
try {}
catch(Exception e){}
it will catch all exceptions that derive from the Exception class (so ALL exceptions). If you have:
try{}
catch (NHibernate.ADOException exception){}
it will only catch exceptions that are or derive from ADOException. So if you get an ArgumentException, it will pass through as if there were no try/catch.
I'm assuming you meant
catch (Exception ex) {}
with the second snippet.
Then the difference is that the first one will only catch one specific type of exception, namely NHibernate.ADOException while the second one will enter the catch block for all exceptions that could possibly be thrown.
The second is usually bad practice since you're claiming to handle every conceivable type of error. However, it can make sense in the outermost scope as a catch-all for any exception that got through.
Using catch { Exception } is strongly not recommended, because this actually hides a bugs. In every place where exception may be thrown, it is necessary to catch only expected exception types, even if this requires to write more code lines. When unexpected exception is thrown, program must crash, this is the only way to fix the bug.

Is an empty catch the same as "catch Exception" in a try-catch statement?

try {
}
catch (Exception) {
}
can I just write
try {
}
catch {
}
Is this ok in C# .NET 3.5? The code looks nicer, but I don't know if it's the same.
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!
Yes, the advantage of the first form is that you can name the exception variable and then use the object to log the exception details to file, etc...
try {
}
catch (Exception ex) {
// Log exception message here...
}
Also, it is generally a bad practice to catch the generic Exception class if you can instead catch specific exceptions (such as an IOException) using the first form.
Edit: As of C# 2.0, non-CLS-compliant exceptions can be caught in both ways.
So, yes. They are identical. A parameter-less catch clause without a Type declaration catches all Exceptions.
In the CLR 2.0, MS introduced RuntimeWrappedException, which is a CLS-compliant exception type, to encapsulate non-CLS-compliant exceptions. The C# compiler still doesn't allow you to throw them, but it can catch them with the catch (Exception) { } syntax.
This is why the C# compiler will issue warning CS1058 if you use both clauses at the same time on CLR 2.0 or later.
Thus, they are in fact identical.
Its the same, but if you put an e after Exception in your first example then you know what exception was thrown...
edit: you should never catch exception, how do you know how to handle it properly?
They are different as noted:
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.
You can see the difference in the IL generated:
//no (Exception)
.try L_0001 to L_0005 catch object handler L_0005 to L_000a
//with (Exception)
.try L_0001 to L_0005 catch [mscorlib]System.Exception handler L_0005 to L_000a
I guess unless you want to use the Exception in some sort, the second one is perfectly fine, though in order to use the exception in the first one, you need to declare a variable like this:
try {
}
catch (Exception e) {
//do something with e
}
Both of your examples appear like you're not doing anything with the exception data. This is generally not a good practice. But both are exactly the same since all exceptions classes are derived from System.Exception.
You should consider doing some type of logging then possibly rethrow the original exception or wrap it in a more specialized exception that your application can understand.
try
{
// Some code here
}
catch(Exception ex)
{
// Do some logging
throw;
}
OR
try
{
// Some code here
}
catch(Exception ex)
{
// Do some logging
// wrap your exception in some custom exception
throw new CustomException("Some custom error message, ex);
}
You should typically only catch exceptions that your code could handle, otherwise it should bubble up and it should eventually be caught by a global exception handler assuming you have one.
Parameter less constructor will cause handling of exception types coming from some other languages, exception which are not inherited from c# SYSTEM.EXCEPTION class.

Categories

Resources