# Exception handling in R TclTk

Here we describe just one possible strategy for catching errors in R Tcl/Tk applications and displaying them in message boxes. If using R Tcl/Tk in Windows, one quickly notices that the RGui main window frequently “gets in the way”, as R Tcl/Tk windows like to hide behind it. It therefore becomes convenient to bypass RGui altogether and just use a batch file to run Rterm with your R TclTk code. Rather than searching for errors in a .Rout file, it is nicer to see errors pop up as you are running the application.

### Try()

We define a Try() function which tries to evaluate an R expression. If the expression evaluates succesfully, then the expected result is returned. If the expression causes an error, then this error is displayed in a message box.

### Try() example

We got an error because we should have used:

Note that if you want to apply Try() to more than one expression at once, you must enclose the expressions within braces.

### A better Try()

This error shown above is useful, but we are not interested in reading the first part of the error message for every single Tcl error, so we will
use a regular expression to track and eliminate it in a refined version of our Try() function for Tcl/Tk commands.

### Failure to load an R package

Below is a function which can be used to try to load a package. If the package cannot be found, an error is displayed in a message box.

### Failure to load a Tcl package

Below is a function which can be used to try to load/require a Tcl package. If the package cannot be found, an error is displayed in a message box.