How to Throw an Exception

Is there a way in Xojo to define my own Exception types and explicitly throw the exception?

In other words, I’d like to define my own Exception that inherits from RuntimeException and when a certain condition that I’d like to capture happens, my code will throw my inherited exception that the try-catch block would then handle.

In this example, I’ve created my own MyCustomInvalidDataEntryException that has 2 properties:

  1. Message (String)
  2. error_id (Integer)

I could then have some code that looks like this (this is purely for illustration purposes):

// Method A
try
   Call SomeMethod()
catch err As MyCustomInvalidDataEntryException
   Messagebox(err.Message + EndOfLine + "Error ID: " + error_id.ToString)
end try

// Method B
SomeMethod()
    // Some code that does something and writes to a logfile if there's an anomaly with the data
   
    If logFile.HasNewEntry Then
        Throw New MyCustomInvalidDataEntryException("Check the Log File for what happened after entering the quarterly financial data.", 144)
    End If
End Method

I think you are looking for Raise Exception, If wrong ignore :grin:
https://documentation.xojo.com/api/language/raise.html

Yes, use Raise:

Raise New MyCustomInvalidDataEntryException("Check the Log File for what happened after entering the quarterly financial data.", 144)

here is a list of different exceptions (below Notes)

Your custom exception class should inherit from RuntimeException so it can be raised (with the “Raise” keyword, as already mentioned). So you don’t need to define the message and code again, they’re already part of the RuntimeException class.

But what if I’d like to have it display a different message & id without coding it into the catch block?

Not sure what you mean?

At some point you will have to set the error number and message you want in code. By far the simplest way is to use the exception constructor method at the same time you raise it, as Martin T already gave an example of above

Raise New MyCustomException("my error message", 144)