Exception handling syntax
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...
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 exceptions
raise Some_Error;
raise Some_Error with "Out of memory"; -- specific diagnostic message
; Exception handling and propagation
with 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;
Ada.Text_IO.Put_Line;
Ada.Text_IO.Put_Line;
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
- !/usr/bin/env bash
- set -e provides another error mechanism
trap print_error exit #list signals to trap
tempfile=`mktemp`
trap "rm $tempfile" exit
./other.sh || echo warning: other failed
echo 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 handler
OPEN "Somefile.txt" FOR INPUT AS #1
CLOSE #1
PRINT "File opened successfully"
END
handler:
PRINT "File does not exist"
END ' RESUME may be used instead which returns control to original position.
C
The most common way to implement exception handling in standard C is to use setjmp/longjmp functions:- include
- include
- include
jmp_buf state;
int main
Microsoft-specific
Two types exist:Example of SEH in C programming language:
int filterExpression
int main
C#
Atry
block must have at least one catch
or finally
clause and at most one finally
clause.public static void Main
C++
- include
In C++, a resource acquisition is initialization technique can be used to clean up resources in exceptional situations. C++ intentionally does not support. The outer braces for the method are optional.
ColdFusion Markup Language (CFML)
Script syntax
try catch finally
Adobe ColdFusion documentation
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
Railo-Lucee specific syntax
Added to the standard syntax above, CFML dialects of Railo and Lucee allow aretry
statement. This statement returns processing to the start of the prior
try
block.CFScript example:
try catch
Tag-syntax example:
D
import std.stdio; // for writefln
int 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 // Exceptions are children of the class Exception.
private
FCustomData: SomeType; // Exceptions may have custom extensions.
public
constructor CreateCustom; // Needs an implementation
property CustomData: SomeType read FCustomData;
end;
; Raising exceptions
raise Exception.Create;
raise Exception.CreateFmt; // See SysUtils.Format for parameters.
raise ECustom.CreateCustom;
; Exception handling and propagation
try // For finally.
try // For except.
... // Code that may raise an exception.
except
on C:ECustom do
begin
... // Handle ECustom.
... if Predicate then...
end;
on S:ESomeOtherException do
begin
// Propagate as an other exception.
raise EYetAnotherException.Create;
end;
on E:Exception do
begin
... // Handle other exceptions.
raise; // Propagate.
end;
end;
finally
// Code to execute whether or not an exception is raised.
end;
Erlang
try
% some dangerous code
catch
throw: -> ok; % handle an exception
error:X -> ok; % handle another exception
_:_ -> ok % handle all exceptions
after
% clean up
end
F#
In addition to the OCaml-basedtry...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
with
| :? System.Net.WebException as ex ->
| :? exn ->
| _ ->
finally
is called and in other system-wide exceptional conditions, 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
let _ =
try
raise ;
printfn "Not reached"
with
| MyException ->
printf "MyException: %s, %d\n" s i
| e ->
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
import Control.Exception
instance Exception Int
instance Exception Double
main = do
catch
prints
in analogy with this C++
- include
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 is supported.
Java
Atry
block must have at least one catch
or finally
clause and at most one finally
clause.try catch finally
JavaScript
The design of JavaScript makes loud/hard errors very uncommon. Soft/quiet errors are much more prevalent. Hard errors propagate to the nearesttry
statement, which must be followed by either a single catch
clause, a single finally
clause, or both.try catch 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;
Another interesting quirk is polymorphism: JavaScript can throw primitive values as errors.
try catch
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 Java
try catch catch
// Approximation #1 in JavaScript
try catch
// Approximation #2 in JavaScript
try catch
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.catch;
Also observe how event handlers can tie into promises as well.
addEventListener;
new Promise;
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
Lisp
Common Lisp
)
))
)
)
Lua
Lua uses thepcall
and xpcall
functions, with xpcall
taking a function to act as a catch
block.; Predefined function
function foo
if x then
return x
else
error "Not a true value"
end
end
function attempt
success, value = pcall
if not success then
else
end
end
attempt
-- Returned: hello
attempt
-- Error: stdin:5: Not a true value
attempt
-- Returned: table: 00809308
if foo then print "Success" end
-- Success
; Anonymous function
if pcall
-- 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
; Raising exceptions
throw MyError
; Exception handling and propagation
try catch catch catch
; Ignoring exceptions - try without catch
try 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 value
my_result = block my_block
Objective-C
; Exception declarationsNSException *exception = ;
; Raising exceptions
@throw exception;
; Exception handling and propagation
@try
@catch
@catch
@catch
@finally
OCaml
exception MyException of string * int
let _ =
try
raise ;
print_endline "Not reached"
with
| MyException ->
Printf.printf "MyException: %s, %d\n" s i
| e ->
Printf.eprintf "Unexpected exception : %s" ;
Printexc.print_backtrace stderr;
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. However, scoping issues can make doing this correctly quite ugly:my ;
if
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 resets the global variable before the checking code.
The following example shows a way to avoid this problem. But at the cost of not being able to use return values:
eval or do ;
Several modules in the Comprehensive Perl Archive Network expand on the basic mechanism:
- provides a set of exception classes and allows use of the try/throw/catch/finally syntax.
- and both allow use of try/catch/finally syntax instead of boilerplate to handle exceptions correctly.
- is a base class and class-maker for derived exception classes. It provides a full structured stack trace in and.
- overloads previously defined functions that return true/false e.g.,,,,, etc. This allows built-in functions and others to be used as if they threw exceptions.
PHP
// Exception handling is only available in PHP versions 5 and greater.
try catch catch finally
PowerBuilder
Exception handling is available in PowerBuilder versions 8.0 and above.
TRY
// Normal execution path
CATCH
// 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
- Statements in which exceptions might be thrown
Version 2.0
Try
Catch
Catch ,
Catch
Python
f = None
try:
f = file
f.write)
except IOError:
except: # catch all exceptions
else: # executed if no exceptions are raised
finally: # clean-up actions, always executed
if f:
f.close
R
tryCatch
,error=function
,finally=
Rebol
REBOL
; ATTEMPT results in the value of the block or the value none on error
print attempt
; User generated exceptions can be any datatype!
example: func
; User generated exceptions can also be named,
; and functions can include additional run time attributes
sophisticated: func
] '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 raised
rescue AnotherError => error
# Here, the exception object is referenced from the
# `error' variable
rescue
# This catches all exceptions derived from StandardError
retry # This executes the begin section again
else
# This is executed only if no exceptions were raised
ensure
# This is always executed, exception or not
end
S-Lang
trycatch SomeError:
catch SomeOtherError:
finally % optional block
New exceptions may be created using the function, e.g.,
new_exception ;
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
on: ExceptionClass
do: .
The general mechanism is provided by the message. 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 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
.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 ERRORNUMBER
'exception handling
Case Else
'unknown exception
End 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 Property
End Class
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
'or
On Error GoTo 0 'switch off error handling. Error causes fatal runtime error and stops application
'or
On 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
'cleanup code, always executed
Exit Sub 'exits procedure
'because we are after Exit Sub statement, next code is hidden for non-error execution
HandlerLabel: '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 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. Typically is used some kind of IDE Add-In, which labels every code line with number before compilation
Resume FinallyLabel
Example of specific 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
.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
Case ERRORNUMBER
'exception handling
Case Is <> 0 'When Err.Number is zero, no error has occurred
'unknown exception
End Select: End With
' *** Try Class ***
Private mstrDescription As String
Private mlngHelpContext As Long
Private mstrHelpFile As String
Private mlngLastDllError As Long
Private mlngNumber As Long
Private mstrSource As String
Public Sub Catch
mstrDescription = Err.Description
mlngHelpContext = Err.HelpContext
mstrHelpFile = Err.HelpFile
mlngLastDllError = Err.LastDllError
mlngNumber = Err.Number
mstrSource = Err.Source
End Sub
Public Property Get Source As String
Source = mstrSource
End Property
Public Property Get Number As Long
Number = mlngNumber
End Property
Public Property Get LastDllError As Long
LastDllError = mlngLastDllError
End Property
Public Property Get HelpFile As String
HelpFile = mstrHelpFile
End Property
Public Property Get HelpContext As Long
HelpContext = mlngHelpContext
End Property
Public Property Get Description As String
Description = mstrDescription
End Property
Visual Basic .NET
ATry
block must have at least one clause Catch
or Finally
clause and at most one Finally
clause.Try
' code to be executed here
Catch 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
Catch ex As Exception
' Handle Exception
Catch
' 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, or when the process crashes due to an exception in another thread.
End Try
Visual Prolog
http://wiki.visual-prolog.com/index.php?title=Language_Reference/Terms#Try-catch-finallytry
% Block to protect
catch TraceId do
% Code to execute in the event of an exception; TraceId gives access to the exception information
finally
% Code will be executed regardles however the other parts behave
end try
X++
public static void Main