BeginPackage["Exceptions`"] Raise::usage = "Raise[exception] raises an exception." Handle::usage = "Handle[cmd, pattern :> action] handles an exception matching pattern." Intercept::usage = "Intercept[symbol::msg, ex] intercepts the given error message and raises ex instead." Exception::uncaught = "Uncaught exception `1`." Begin["`Private`"] (* raise exceptions *) `errorCookie (* special value returned by Throw *) Raise[ error_ ] := Throw[errorCookie, error] (* handle exceptions *) SetAttributes[Handle, {HoldFirst}] Handle[ try_, (pattern_ :> action_)|(pattern_ -> action_)] := Catch[try, pattern, exec[pattern :> action]] (* several handlers *) Handle[try_, first_, rest__] := Handle[Handle[try, first], rest] (* apply handler *) exec[rule_][ errorCookie, error_ ] := Replace[error, rule] (* not called through Raise[], but through Throw[]: pass on *) exec[rule_][ junk__ ] := Throw[junk] (* intercept error messages *) SetAttributes[Intercept, {HoldFirst}] Intercept[msg_MessageName, ex_] := Module[{protected}, protected = Unprotect[Message]; Message[msg, ___] := Raise[ex]; Protect[Evaluate[protected]]; ] (* install global error handler *) If[ !TrueQ[$installed], (* install it *) If[!ValueQ[$Pre], $Pre=Identity]; $oldPre = $Pre; (* old value *) $Pre = Function[{expr}, Handle[$oldPre[expr], e_ :> Message[Exception::uncaught, e]], {HoldFirst}]; $installed = True; (* do it only once *) ] End[] Protect[ Handle, Raise, Intercept ] EndPackage[]