Why is catching "Exception" not ambiguous when I have System.Exception and MyNamespace.Exception?
In my C# code, I have access to a MyNamespace.Exception
as well as a System.Exception
. When I want to catch one of those exceptions, ideall开发者_Python百科y I'd fully qualify which one I want to catch or use aliasing to make it clear. However, I'm concerned that it's all to easy to just type catch(Exception)
. I assumed that the compiler would flag this up as an ambiguous name, however it doesn't. It always assumes I'm want a MyNamespace.Exception
which clearly leaves a hole for many exceptions to miss the catch if I meant to use a System.Exception
. This is not just a problem with Exception
, I also have exceptions such as MyNamespace.ArgumentException
.
So my question is why does the compiler not complain about an ambiguous exception type? Also, how would you go about protecting against this problem?
why does the compiler not complain about an ambiguous exception type?
Probably because it is not ambiguous the way you've stated it. If you said:
using MyNamespace;
using System;
class P
{
void M()
{
try { ... } catch(Exception) { ... }
then it would be ambiguous because it is not clear which "using" directive is the relevant one; both could work.
If you said
using System;
namespace MyNamespace
{
class P
{
void M()
{
try { ... } catch(Exception) { ... }
Then it is not ambiguous; stuff in the current namespace takes priority over stuff imported by a using directive.
how would you go about protecting against this problem?
I would not get into the situation in the first place. Naming your types the same as common system types is confusing, dangerous and contrary to good design principles.
Types in the current namespace have priority over other types.
The reason why this happens has to do with the way the C# compiler resolves names. In short it will prefer a name which exists in the current namespace to one in a namespace which is imported.
The first step to preventing this problem is to not define types which have the same name as types in the System
namespace. Doing this will only lead you to potential ambiguous names (to the developer). Instead choose unambiguous names like MyException
or MyArgumentException
.
I would not name my exception Exception
. Instead name it something else (like myException
).
精彩评论