How to: User-defined RunTimeException

Hello,

after an extensive occupation with exceptions, I’m still not quite sure how to handle user-defined exceptions.

Let’s say I have a class “Foo” and a class “FooException” derived from RuntimeException. By means of Try…Catch I can now trigger it in case of a problem:

Try // Your code here Catch e As FooException MsgBox("An exception of type " + e.Type " + was caught. " + e.Message) End Try
RuntimeException, for example, has the Message property. How can I create/display my own error messages for my class FooException?

Do I have to create a Type property within FooException which then returns the error from an enumeration, for example?

Can someone please write a little “How to” or “Step by Step” tutorial here that shows how to create and call your own exceptions?

Thanks!

dim r as new RuntimeException R.message = “Hello” Raise r

But it may be better to subclass and make your own exception class with a constructor taking message as parameter.

Thank you, Christian. So I understand you correctly that a subclass of RuntimeException is only helpful in the sense that the name of the exception class can be used to get a better indication of the area of the error? So I could also simply throw a RuntimeException without deriving a subclass from it? Are there no advantages of an own subclass?

if there were no advnatage to defining our own datatypes everything would just be “memory” and we’d write all the code to see if its a string, or an integer, or a ptr or a variant or whatever else

by defining your own exception type you no longer have to catch EVERY runtime exception and then examine it to see if its one of the ones youre specifically interested in

instead of

try
     // whatever code
catch exc as runtimeexception
   // now examine the message or something else to see IF it s one we can handle 
   // and want to do something special about
end try

you can write

try
     // whatever code
catch exc as MyRuntimeException
    // now you KNOW its something specific and you can take specific actions to deal with the exception
end try

OR

try
     // whatever code
catch exc as MyFirstExceptionType
    // now you KNOW its something specific and you can take specific actions to deal with the exception
catch exc as MySecondExceptionType
    // now you KNOW its something specific and you can take specific actions to deal with the exception
end try

etc

That’s cool, Norman, thanks.