Catching any exception regardless of type

I can’t find anything in the docs about catching an exception other than a very specific one. Usually in .NET I prefer something like:

Catch ex As Exception

… where all more specific exception classes inherit from Exception, as a default. I assume this is the Xojo equivalent?

Catch ex As RuntimeException

Although the documentation doesn’t cover it, by my experimentation it looks like you can have multiple Catches in a Try/Catch block, which is great.

My view has always been that, yes, I’m e.g. making a DB call so the most likely error is a DatabaseException but I don’t know all possible edge cases (out of memory, etc) and if all I want to do is to log the stack trace and error message and notify the user and recover gracefully, I really don’t care about the type of exception in most cases. I wouldn’t want to have 2 or 3 or 10 Catch blocks to cover the possibilities, so I’m hoping one can just call a superclass of all Exceptions and get it all handled in one spot.

As far as I understand, App.UnhandledException is where an exception will be caught if it has not been caught anywhere else. Kind of last resort, or the place where all exceptions can be handled.

I’m aware of that but am looking for an in-place catch hierarchy where the most specific handled exception type is caught (if more than one catch is specified) and if all else fails, the base, most general exception is caught. If I use the unhandled app-level catch then I lose control of cleaning up or exiting gracefully at the point of exception.

Try
Catch
//ALL exceptions will go into here if you dont catch a specific one
//if you start guessing which ones are likely, it gets very messy in a hurry, IME
end try
2 Likes

Some meaningless example code:

try
  // some code
catch ex as KeyNotFoundException
  // handle that
catch ex as OutOfBoundsException
  // or that
catch ex as RuntimeException
  // anything else
end try
1 Like

Warning: If you catch RuntimeException generally, you will also catch EndException and ThreadEndException, which are not errors, they are used internally to indicate that a Thread has been stopped or that app is quitting. You should re-raise either of those exceptions.

catch ex as RuntimeException
  if ex isa EndException or ex isa ThreadEndException then
    raise ex
  end if

  // Now handle it
end try
4 Likes

You can also just put “Exception” at the bottom of the method, if an exception should mean that nothing at all in the method should fire.

1 Like

Right, but that should be used rarely. Generally, you want to deal with specific exceptions that might occur at certain points in code.

4 Likes

Yes, this is pretty much restricted to cases where the whole method’s Plan B is “do this instead” or “don’t do anything.” :slight_smile:

1 Like

Thanks everyone, that confirms my assumptions perfectly. :slightly_smiling_face: