Exception handling syntax explained

Exception handling syntax is the set of keywords and/or structures provided by a computer programming language to allow exception handling, which separates the handling of errors that arise during a program's operation from its ordinary processes. Syntax for exception handling varies between programming languages, partly to cover semantic differences but largely to fit into each language's overall syntactic structure. Some languages do not call the relevant concept "exception handling"; others may not have direct facilities for it, but can still provide means to implement it.

Most commonly, error handling uses a try...[catch...][finally...] block, and errors are created via a throw statement, but there is significant variation in naming and syntax.

Catalogue of exception handling syntaxes

Ada

Exception declarationsSome_Error : exception;
Raising exceptionsraise Some_Error;

raise Some_Error with "Out of memory"; -- specific diagnostic message

Exception handling and propagationwith Ada.Exceptions, Ada.Text_IO;

procedure Foo is Some_Error : exception;begin Do_Something_Interesting;exception -- Start of exception handlers when Constraint_Error => ... -- Handle constraint error when Storage_Error => -- Propagate Storage_Error as a different exception with a useful message raise Some_Error with "Out of memory"; when Error : others => -- Handle all others Ada.Text_IO.Put("Exception: "); Ada.Text_IO.Put_Line(Ada.Exceptions.Exception_Name(Error)); Ada.Text_IO.Put_Line(Ada.Exceptions.Exception_Message(Error));end Foo;

Assembly language

Most assembly languages will have a macro instruction or an interrupt address available for the particular system to intercept events such as illegal op codes, program check, data errors, overflow, divide by zero, and other such. IBM and Univac mainframes had the STXIT macro. Digital Equipment Corporation RT11 systems had trap vectors for program errors, i/o interrupts, and such. DOS has certain interrupt addresses. Microsoft Windows has specific module calls to trap program errors.

Bash

  1. !/usr/bin/env bash
  2. set -e provides another error mechanism

print_errortrap print_error exit #list signals to traptempfile=`mktemp`trap "rm $tempfile" exit./other.sh || echo warning: other failedecho oops)echo never printed

One can set a trap for multiple errors, responding to any signal with syntax like:

BASIC

An On Error goto/gosub structure is used in BASIC and is quite different from modern exception handling; in BASIC there is only one global handler whereas in modern exception handling, exception handlers are stacked.

ON ERROR GOTO handlerOPEN "Somefile.txt" FOR INPUT AS #1CLOSE #1PRINT "File opened successfully"END

handler:PRINT "File does not exist"END ' RESUME may be used instead which returns control to original position.

C

C does not provide direct support to exception handling: it is the programmer's responsibility to prevent errors in the first place and test return values from the functions.

In any case, a possible way to implement exception handling in standard C is to use setjmp/longjmp functions:

  1. include
  2. include
  3. include

enum exception;jmp_buf state;

int main(void)

Microsoft-specific

Two types exist:

Example of SEH in C programming language:int filterExpression (EXCEPTION_POINTERS* ep) int main(void)

C#

A try block must have at least one catch or finally clause and at most one finally clause.public static void Main

C++

  1. include

int main In C++, a resource acquisition is initialization technique can be used to clean up resources in exceptional situations. C++ intentionally does not support .[1] The outer braces for the method are optional.

ColdFusion Markup Language (CFML)

Script syntax

try catch (any e) finally

Adobe ColdFusion documentation[2]

Tag syntax

code that may cause an exception First level of exception handling code Second level of exception handling code final code Adobe ColdFusion documentation[3]

Railo-Lucee specific syntax

Added to the standard syntax above, CFML dialects of Railo and Lucee allow a retry statement.[4]

This statement returns processing to the start of the prior try block.

CFScript example:try catch (any e)

Tag-syntax example:

D

import std.stdio; // for writeflnint main In D, a clause or the resource acquisition is initialization technique can be used to clean up resources in exceptional situations.

Delphi

Exception declarationstype ECustom = class(Exception) // Exceptions are children of the class Exception. private FCustomData: SomeType; // Exceptions may have custom extensions. public constructor CreateCustom(Data: SomeType); // Needs an implementation property CustomData: SomeType read FCustomData; end;
Raising exceptionsraise Exception.Create('Message');

raise Exception.CreateFmt('Message with values: %d, %d',[value1, value2]); // See SysUtils.Format for parameters.

raise ECustom.CreateCustom(X);

Exception handling and propagation[5] try // For finally. try // For except. ... // Code that may raise an exception. except on C:ECustom do begin ... // Handle ECustom. ... if Predicate(C.CustomData) then ... end; on S:ESomeOtherException do begin // Propagate as an other exception. raise EYetAnotherException.Create(S.Message); end; on E:Exception do begin ... // Handle other exceptions. raise; // Propagate. end; end; finally // Code to execute whether or not an exception is raised (e.g., clean-up code).end;

Erlang

try % some dangerous codecatch throw: -> ok; % handle an exception error:X -> ok; % handle another exception _:_ -> ok % handle all exceptionsafter % clean upend

F#

In addition to the OCaml-based try...with, F# also has the separate try...finally construct, which has the same behavior as a try block with a finally clause in other .NET languages.

For comparison, this is a translation of the C# sample above.try try (* Code that could throw an exception. *) with | :? System.Net.WebException as ex -> (* Handles a WebException. The exception object is stored in "ex". *) | :? exn -> (* Handles any CLR exception. Since the exception has not been given an identifier, it cannot be referenced. *) | _ -> (* Handles anything that might be thrown, including non-CLR exceptions. *)finally (* Always run when leaving the try block, regardless of whether any exceptions were thrown or whether they were handled. Often used to clean up and close resources such a file handles. May not be run when Environment.FailFast is called and in other system-wide exceptional conditions (e.g. power loss), or when the process crashes due to an exception in another thread. *)

For comparison, this is translation of the OCaml sample below.exception MyException of string * int (* exceptions can carry a value *)let _ = try raise (MyException ("not enough food", 2)); printfn "Not reached" with | MyException (s, i) -> printf "MyException: %s, %d\n" s i | e -> (* catch all exceptions *) eprintf "Unexpected exception : %O" e; eprintf "%O" e.StackTrace

Haskell

Haskell does not have special syntax for exceptions. Instead, a ///. interface is provided by functions.

import Prelude hiding(catch)import Control.Exceptioninstance Exception Intinstance Exception Doublemain = do catch (catch (throw (42::Int)) (\e-> print (0,e::Double))) (\e-> print (1,e::Int))

prints

(1,42)

in analogy with this C++

  1. include

using namespace std;int main

Another example is

do `catch` \ex -> do

In purely functional code, if only one error condition exists, the type may be sufficient, and is an instance of Haskell's class by default. More complex error propagation can be achieved using the or monads, for which similar functionality (using) is supported.

Java

A try block must have at least one catch or finally clause and at most one finally clause.try catch (ExampleException ee) finally

JavaScript

The design of JavaScript makes loud/hard errors very uncommon. Soft/quiet errors are much more prevalent. Hard errors propagate to the nearest try statement, which must be followed by either a single catch clause, a single finally clause, or both.try catch(error) finally

If there is no try statement at all, then the webpage does not crash. Rather, an error is logged to the console and the stack is cleared. However, JavaScript has the interesting quirk of asynchronous externally-invoked entry points. Whereas, in most other languages, there is always some part of the code running at all times, JavaScript does not have to run linearly from start to end. For example, event listeners, Promises, and timers can be invoked by the browser at a later point in time and run in an isolated but shared context with the rest of the code. Observe how the code below will throw a new error every 4 seconds for an indefinite period of time or until the browser/tab/computer is closed.setInterval(function, 4000);

Another interesting quirk is polymorphism: JavaScript can throw primitive values as errors.try catch(error)

Note that the catch clause is a catch-all, which catches every type of error. There is no syntaxical ability to assign different handlers to different error types aside from experimental and presently removed Gecko extensions from many years ago. Instead, one can either propagate the error by using a throw statement inside the catch statement, or use multiple conditional cases. Let us compare an example in Java and its rough equivalents in JavaScript.// Example in Javatry catch(NullPointerException error) catch(ArithmeticException error) // Approximation #1 in JavaScripttry catch(error) // Approximation #2 in JavaScripttry catch(error)

Another aspect of exceptions are promises, which handle the exception asynchronously. Handling the exception asynchronously has the benefit that errors inside the error handler do not propagate further outwards.new Promise(function).catch(function(err));Also observe how event handlers can tie into promises as well.addEventListener("unhandledrejection", function(event));

new Promise(function);

Lastly, note that, as JavaScript uses mark-and-sweep garbage-collection, there is never any memory leakage from throw statements because the browser automatically cleans dead objects - even with circular references.try catch(error)

Lisp

Common Lisp

(ignore-errors (/ 1 0))

(handler-case (progn (print "enter an expression") (eval (read))) (error (e) (print e)))

(unwind-protect (progn (print "enter an expression") (eval (read))) (print "This print will always be executed, similar to finally."))

Lua

Lua uses the pcall and xpcall functions, with xpcall taking a function to act as a catch block.

Predefined functionfunction foo(x) if x then return x else error "Not a true value" endend

function attempt(arg) success, value = pcall(foo, arg)

if not success then print("Error: " .. tostring(value)) else print("Returned: " .. tostring(value)) endend

attempt("hello") -- Returned: hello

attempt(nil) -- Error: stdin:5: Not a true value

attempt -- Returned: table: 00809308 if foo(42) then print "Success" end -- Success

Anonymous functionif pcall(function -- Do something that might throw an error. end) then print "No errors" -- Executed if the protected call was successful.else print "Error encountered" -- Executed if the protected call failed.end

print "Done" -- Will always be executed

Next Generation Shell

Defining custom exception typetype MyError(Error)
Raising exceptionsthrow MyError("this happened")
Exception handling and propagationtry catch(e:MyError) catch(e:MyError) catch(e:Error)
Ignoring exceptions - try without catchtry 1/0 # evaluates to null
Ignoring exceptions - "tor" operator"tor" is try-or operator. In case of any exception when evaluating the argument on the left, evaluates to the argument on the right.1/0 tor 20 # evaluates to 20
"block" - facility to use exceptions to return a valuemy_result = block my_block

Objective-C

Exception declarationsNSException *exception = [NSException exceptionWithName:@"myException" reason:@"yourReason" userInfo:nil];
Raising exceptions@throw exception;
Exception handling and propagation@try @catch (SomeException *se) @catch (NSException *ne) @catch (id ue) @finally

OCaml

exception MyException of string * int (* exceptions can carry a value *)let _ = try raise (MyException ("not enough food", 2)); print_endline "Not reached" with | MyException (s, i) -> Printf.printf "MyException: %s, %d\n" s i | e -> (* catch all exceptions *) Printf.eprintf "Unexpected exception : %s" (Printexc.to_string e); (*If using Ocaml >= 3.11, it is possible to also print a backtrace: *) Printexc.print_backtrace stderr; (* Needs to beforehand enable backtrace recording with Printexc.record_backtrace true or by setting the environment variable OCAMLRUNPARAM="b1"*)

Perl 5

The Perl mechanism for exception handling uses to throw an exception when wrapped inside an block. After the, the special variable contains the value passed from .

Perl 5.005 added the ability to throw objects as well as strings. This allows better introspection and handling of types of exceptions.

eval ;if ($@)

The pseudo-signal can be trapped to handle calls to . This is not suitable for exception handling since it is global. However it can be used to convert string-based exceptions from third-party packages into objects.

local $SIG = sub ;

The forms shown above can sometimes fail if the global variable is changed between when the exception is thrown and when it is checked in the statement. This can happen in multi-threaded environments, or even in single-threaded environments when other code (typicallycalled in the destruction of some object) resets the global variable before the checking code.The following example shows a way to avoid this problem (see http://www.perlfoundation.org/perl5/index.cgi?exception_handling or https://stackoverflow.com/a/10343025; cf. http://mvp.kablamo.org/essentials/die-eval/). But at the cost of not being able to use return values:

eval or do ;

Several modules in the Comprehensive Perl Archive Network (CPAN) expand on the basic mechanism:

PHP

// Exception handling is only available in PHP versions 5 and greater.try catch (FirstExceptionClass $exception) catch (SecondExceptionClass $exception) finally

PowerBuilder

Exception handling is available in PowerBuilder versions 8.0 and above.

TRY
   // Normal execution path
CATCH (ExampleException ee)
   //  deal with the ExampleException
FINALLY
   // This optional section is executed upon termination of any of the try or catch blocks above
END TRY

PowerShell

Version 1.0

trap [Exception]

  1. Statements in which exceptions might be thrown

Version 2.0

Try Catch [Exception1] Catch [Exception2],[Exception3etc] Catch

Python

f = Nonetry: f = open("aFileName", "w") f.write(could_make_error)except IOError: print("Unable to open file")except: # catch all exceptions print("Unexpected error")else: # executed if no exceptions are raised print("File write completed successfully")finally: # clean-up actions, always executed if f: f.close

R

tryCatch(specialError=function(e),error=function(e),finally=)

Rebol

REBOL [Title: "Exception and error handling examples" ]

TRY a block; capturing an error! and converting to object!if error? exception: try [1 / 0][probe disarm exception]
ATTEMPT results in the value of the block or the value none on errorprint attempt [divide 1 0]
User generated exceptions can be any datatype!example: func ["A function to throw an exception" ][throw "I'm a string! exception" ]catch [example]
User generated exceptions can also be named,
  • and functions can include additional run time attributes sophisticated: func ["A function to throw a named error exception" [catch]][throw/name make error! "I'm an error! exception" 'moniker ]catch/name [sophisticated] 'moniker
  • Rexx

    signal on halt; do a = 1 say a do 100000 /* a delay */ end end halt: say "The program was stopped by the user" exit

    Ruby

    begin # Do something nifty raise SomeError, "This is the error message!" # Uh-oh!rescue SomeError # This is executed when a SomeError exception # is raisedrescue AnotherError => error # Here, the exception object is referenced from the # `error' variablerescue # This catches all exceptions derived from StandardError retry # This executes the begin section againelse # This is executed only if no exceptions were raisedensure # This is always executed, exception or notend

    S-Lang

    try catch SomeError: catch SomeOtherError: finally % optional block

    New exceptions may be created using the function, e.g., new_exception ("MyIOError", IOError, "My I/O Error");will create an exception called as a subclass of . Exceptions may be generated using the throw statement, which can throw arbitrary S-Lang objects.

    Smalltalk

    ["code that might throw an exception" ] on: ExceptionClass do: [:ex | "code that handles exception" ].

    The general mechanism is provided by the message .[6] Exceptions are just normal objects that subclass, you throw one by creating an instance and sending it a message, e.g., . The handling mechanism is again just a normal message implemented by . The thrown exception is passed as a parameter to the handling block closure, and can be queried, as well as potentially sending to it, to allow execution flow to continue.

    Swift

    Exception handling is supported since Swift 2.enum MyException : ErrorType func someFunc throws do catch MyException.Foo(let s, let i) catch

    Tcl

    if Since Tcl 8.6, there is also a try command:try on ok trap ListPattern1 trap ListPattern2 on error finally

    VBScript

    With New Try: On Error Resume Next 'do Something (only one statement recommended).Catch: On Error GoTo 0: Select Case .Number Case 0 'this line is required when using 'Case Else' clause because of the lack of "Is" keyword in VBScript Case statement 'no exception Case SOME_ERRORNUMBER 'exception handling Case Else 'unknown exceptionEnd Select: End With

    ' *** Try Class ***Class Try Private mstrDescription Private mlngHelpContext Private mstrHelpFile Private mlngNumber Private mstrSource

    Public Sub Catch mstrDescription = Err.Description mlngHelpContext = Err.HelpContext mstrHelpFile = Err.HelpFile mlngNumber = Err.Number mstrSource = Err.Source End Sub

    Public Property Get Source Source = mstrSource End Property Public Property Get Number Number = mlngNumber End Property

    Public Property Get HelpFile HelpFile = mstrHelpFile End Property Public Property Get HelpContext HelpContext = mlngHelpContext End Property Public Property Get Description Description = mstrDescription End PropertyEnd Class[7]

    Visual Basic 6

    Exception handling syntax is very similar to Basic. Error handling is local on each procedure.On Error GoTo HandlerLabel 'When error has occurred jumps to HandlerLabel, which is defined anywhere within Function or Sub'orOn Error GoTo 0 'switch off error handling. Error causes fatal runtime error and stops application'orOn Error Resume Next 'Object Err is set, but execution continues on next command. You can still use Err object to check error state.'...Err.Raise 6 ' Generate an "Overflow" error using build-in object Err. If there is no error handler, calling procedure can catch exception by same syntax'...

    FinallyLabel: 'just common label within procedure (non official emulation of Finally section from other languages) 'cleanup code, always executedExit Sub 'exits procedure

    'because we are after Exit Sub statement, next code is hidden for non-error executionHandlerLabel: 'defines a common label, here used for exception handling.If Err.Number = 6 Then 'Select Case statement is typically better solution Resume FinallyLabel 'continue execution on specific label. Typically something with meaning of "Finally" in other languages 'or Resume Next 'continue execution on statement next to "Err.Raise 6" 'or Resume 'continue execution on (repeat) statement "Err.Raise 6"End If

    MsgBox Err.Number & " " & Err.Source & " " & Erl & " " & Err.Description & " " & Err.LastDllError 'show message box with important error properties 'Erl is VB6 build-in line number global variable (if used). Typically is used some kind of IDE Add-In, which labels every code line with number before compilationResume FinallyLabel

    Example of specific (non official) implementation of exception handling, which uses object of class "Try". With New Try: On Error Resume Next 'Create new object of class "Try" and use it. Then set this object as default. Can be "Dim T As New Try: ... ... T.Catch 'do Something (only one statement recommended).Catch: On Error GoTo 0: Select Case .Number 'Call Try.Catch procedure. Then switch off error handling. Then use "switch-like" statement on result of Try.Number property (value of property Err.Number of build-in Err object) Case SOME_ERRORNUMBER 'exception handling Case Is <> 0 'When Err.Number is zero, no error has occurred 'unknown exceptionEnd Select: End With

    ' *** Try Class ***Private mstrDescription As StringPrivate mlngHelpContext As LongPrivate mstrHelpFile As StringPrivate mlngLastDllError As LongPrivate mlngNumber As LongPrivate mstrSource As String

    Public Sub Catch mstrDescription = Err.Description mlngHelpContext = Err.HelpContext mstrHelpFile = Err.HelpFile mlngLastDllError = Err.LastDllError mlngNumber = Err.Number mstrSource = Err.SourceEnd Sub

    Public Property Get Source As String Source = mstrSourceEnd Property

    Public Property Get Number As Long Number = mlngNumberEnd Property

    Public Property Get LastDllError As Long LastDllError = mlngLastDllErrorEnd Property

    Public Property Get HelpFile As String HelpFile = mstrHelpFileEnd Property

    Public Property Get HelpContext As Long HelpContext = mlngHelpContextEnd Property

    Public Property Get Description As String Description = mstrDescriptionEnd Property

    Visual Basic .NET

    A Try block must have at least one clause Catch or Finally clause and at most one Finally clause.Try ' code to be executed hereCatch ex As Exception When condition ' Handle Exception when a specific condition is true. The exception object is stored in "ex".Catch ex As ExceptionType ' Handle Exception of a specified type (i.e. DivideByZeroException, OverflowException, etc.)Catch ex As Exception ' Handle Exception (catch all exceptions of a type not previously specified)Catch ' Handles anything that might be thrown, including non-CLR exceptions.Finally ' Always run when leaving the try block (including catch clauses), regardless of whether any exceptions were thrown or whether they were handled. ' Often used to clean up and close resources such a file handles. ' May not be run when Environment.FailFast is called and in other system-wide exceptional conditions (e.g. power loss), or when the process crashes due to an exception in another thread.End Try

    Visual Prolog

    try % Block to protectcatch TraceId do % Code to execute in the event of an exception; TraceId gives access to the exception informationfinally % Code will be executed regardles however the other parts behaveend try[8]

    X++

    public static void Main(Args _args)

    See also

    Notes and References

    1. http://www.stroustrup.com/bs_faq2.html#finally Bjarne Stroustrup's FAQ
    2. Web site: Handling exceptions . 2014-01-01 . https://web.archive.org/web/20140102193946/https://learn.adobe.com/wiki/display/coldfusionen/Handling+exceptions . 2014-01-02 . dead .
    3. Web site: Exception handling tags . 2014-01-01 . https://web.archive.org/web/20140102192259/https://learn.adobe.com/wiki/display/coldfusionen/Exception+handling+tags . 2014-01-02 . dead .
    4. https://issues.jboss.org/browse/RAILO-2176
      1. JBoss Community issue tracker ticket for adding retry
    5. Borland, Delphi Version 7.0, Online help
    6. Web site: Pharo by Example . 2010-03-20 . https://web.archive.org/web/20091021035635/http://pharobyexample.org/ . 2009-10-21 . dead .
    7. Web site: Try-Catch for VB . 2012-03-17 . 2016-04-16 . https://web.archive.org/web/20160416093023/https://sites.google.com/site/truetryforvisualbasic/ . dead .
    8. http://wiki.visual-prolog.com/index.php?title=Language_Reference/Terms#Try-catch-finally