Azurewrath

Hi all,

1. Basically what I want to do is to implement an exception that will work like .net's, that will halt the compile process and popup a message.

2. I also want it to be isolated from my custom library, same assembly but different files like so:

MyExceptions.OutOfMindException();

I know how to do #2, but not #1.

Is this an optimal way of writing your own exceptions

Btw someone told me this is the code to use:

[global:: System.Serializable]

public class MyException : Exception

{

//

// For guidelines regarding the creation of new exception types, see

// http://msdn.microsoft.com/library/default.asp url=/library/en-us/cpgenref/html/cpconerrorraisinghandlingguidelines.asp

// and

// http://msdn.microsoft.com/library/default.asp url=/library/en-us/dncscol/html/csharp07192001.asp

//

public MyException() { }

public MyException(string message) : base(message) { }

public MyException(string message, Exception inner) : base(message, inner) { }

protected MyException(

System.Runtime.Serialization.SerializationInfo info,

System.Runtime.Serialization.StreamingContext context)

: base(info, context) { }

}


But I don't know what to type inside those empty braces Is this enough to do the job




Thanks,

Aw





Re: Visual C# Language Implementing Custom Exceptions

Frank Boyne

First thing you should think about is whether there is an existing exception that you can use instead. There really isn't any point inventing a MyVeryOwnNotFoundFileException if the existing FileNotFoundException will do the job. It is much kinder to throw a FileNotFoundException and save programmers from the bother of figuring out what the difference between that and your own exception is.

It seems to me that there are two reasons to create a new exception.

One reason is to provide additional data that doesn't exist in the base Exception class. For example, the FileNotFoundException class adds the FileName and FusionLog properties to the standard seven properties inherited from Exception. Often, such an exception will also declare new constructors to allow the exception to be easily constructed with values for these new properties. FileNotFoundException for example has several new constructors with an additional string parameter to allow the caller to provide a value for the FileName property.

The other reason for a new Exception is to provide an Exception type that can be caught separately from all existing types (and so can be processed in a different way). For example, the types AccessViolationException and ArithmeticViolationException are identical in shape to the Exception type (same properties and methods). Having two separate exceptions allows programmers to catch each one separately and so handle each one separately.

The code you quote is useful for an Exception created for the second of the two reasons and less useful for an Exception created for the first of the two reasons. MyException will behave exactly as an Exception would behave, nothing more.

For example, when the MyException (string message) constructor is called, the equivalent base constructor, i.e., Exception (string message), is called passing the message parameter into it. Since the braces are empty, the constructor does nothing else - which is what you want if you are trying to create a class that behaves the same way the Exception class behaves but which has a different name.

If you were trying to create an exception that provided additional properties, the curly braces might contain logic to set default values for those properties (if such logic was necessary). You would probably also create new constructors that allowed you to construct instances with non-default values for those new properties (or at least some of them).

One final not very relevant observation: the use of the global:: namespace alias qualifier is either not really needed or not used enough in the code you quoted.

The qualifier is useful when complex namespace definitions may have hidden the namespace you are trying to access. Thus global:: System.Serializable allows you to access the Serializable class in the root System namespace even if another System namespace has been defined. But, if the global:: qualifier is required to guarantee you access to the Serializable class then it is also required to guarantee you access to the Exception class and to the SerializationInfo and StreamingContext classes.

Most likely you can get away without using the qualifier altogether, e.g.,

Code Snippet

[Serializable]

public class MyException : Exception

{

// . . . etc . . .

If you really do need the qualifier (or want to use it 'just in case'), then you need to use it consistently

Code Snippet

[global:: System.Serializable]

public class MyException : global:: System.Exception

{

// . . . etc . . .





Re: Visual C# Language Implementing Custom Exceptions

Azurewrath

Thanks for replying.

When the exception occurs, I get this message in the output window:

A first chance exception of type 'MyException' occurred in MathEx.dll

I wonder if I can get a halt in the compile similar to default exceptions work, and shows a popup about the problem Or maybe something that shows up in the error list, and doesn't let you to compile




Thanks again,
Aw




Re: Visual C# Language Implementing Custom Exceptions

Nimrand

Exceptions thrown at runtime should work the same whether they are exception types defined by you or by one of the .NET framework libraries. You might want to make sure that the debugger is configured correctly, however. Make sure that it is set to halt whenever exceptions of any type are thrown, and not just when they are thrown and not handled. What you are describing may be that the debugger isn't halting on your custom exceptions because its getting caught by the Windows Forms API, which will then throw up a dialog like the one you describe. Since the exception is caught and "handled," the debugger will not pause the program unless its configured to do so.

You can't really add your own compile-time errors. C# has the #error directive, but I don't think this will be useful to you, since it can really only make errors based upon what build symbols are defined. You can follow certain class design guidelines, however, that will cause more programmer mistakes to be caught, however. For instance, using strongly-typed collections will catch more coding errors than using weakly-typed collections.





Re: Visual C# Language Implementing Custom Exceptions

Frank Boyne

Azurewrath wrote:
When the exception occurs, I get this message in the output window:

A first chance exception of type 'MyException' occurred in MathEx.dll

That means the exception is being thrown. Do you have a try/catch block around the code that causes the exception to be thrown Or the code that calls the code that causes the exception to be thrown Or the code that calls the code that calls...

The exception helper pop-up only appears if the exception is unhandled. If some piece of code uses a try-catch block to handle the exception then the helper won't pop up.





Re: Visual C# Language Implementing Custom Exceptions

Azurewrath

Thanks guys. Very helpful.

I remember getting these popup error messages. So since you said they come from unhandled exceptions, can you give me an example for me to try

Also if the compiler only tells you that an exception occured with the name of the exception, what's the use of 3 constructors in an exception class. I mean one takes a string parameter, but if I pass something, it doesn't show up in the output window, so where do we or the user sees it

Lastly if this error occurs after you run a compile exe, then what happens The program terminates right





Thanks again,
Aw




Re: Visual C# Language Implementing Custom Exceptions

Frank Boyne

Azurewrath wrote:
I remember getting these popup error messages. So since you said they come from unhandled exceptions, can you give me an example for me to try

Create a C# console application. Modify main by pasting the code below into it then run the program in the debugger by pressing F5. You'll see two "Fiorst time exception" messages in the output window and you'll get the Exception helper popping up for the second unhandled one.

Code Snippet

static void Main(string[] args)

{

try

{

throw new MyCustomException("this exception gets caught - no handler");

}

catch (MyCustomException ex)

{

// do nothing with the exception

}

throw new MyCustomException ("this exception does not get caught");

}

Also if the compiler only tells you that an exception occured with the name of the exception, what's the use of 3 constructors in an exception class. I mean one takes a string parameter, but if I pass something, it doesn't show up in the output window, so where do we or the user sees it

It has nothing to do with the compiler. Exceptions are thrown at run-time not at compile time and are processed by the CLR. The output window in this case is giving only minimal information because uyou are running the program within the debugger. Either the exception is handled in which case you don;t really care about the details or it isn;t handled in which case the Exception Helper will step in so why clutter up the Output window with unncessary detail that can be more easily accessed via the helper

Open a Command Window, navigate to the bin\debug folder of the console program you just created and run the exe from the window. If the Just In Time Debugger asks if you want to debug say no (or cancel). You'll see some more details of the exception because now the failure wasn't processed by the debugger.

Replace the "do nothing" comment above with some calls to Console.Writeline passing in the variable ex or one of its properties and you'll see more details about the exception on the console window.

Lastly if this error occurs after you run a compile exe, then what happens The program terminates right

If an application program throws an exception and that exception isn't handled by a try-catch block the application is normally terminated.

There are some cases where that isn't true. For example, if a Windows Forms application suffers an unhandled excpetion on the main application thread the Application.ThreadException event will be raised. If that event is handled by the application then the default behaviour is that the application is not terminated. You can change that default behaviour by calling Application.SetUnhandledExceptionMode.





Re: Visual C# Language Implementing Custom Exceptions

Azurewrath

Thanks alot again. That made me understand it better.

But I guess the Console.WriteLine was just to print the message to the output window.

Basically what I want to do is:

1. Encapsulate the throw exception statement in a method, like MyExceptions.InsufficientDiskSizeException()

2. Pass some arguments to the method when applicable, like MyExceptions.ArgumentOutOfRangeException(value), which could in a way tell the user something like this:

"Length can be between 0 and 1, got 76."

3. All messages and the method definitions will be in a different file for the project, and if there is already an exception for what I want, I will just call one of its constructors.


Is this reasonable




Thanks again,
Aw