Movatterモバイル変換


[0]ホーム

URL:


Jump to content
WikipediaThe Free Encyclopedia
Search

Exception handling syntax

From Wikipedia, the free encyclopedia
Keywords provided by a programming language
This articleusesbare URLs, which are uninformative and vulnerable tolink rot. Please consider converting them tofull citations to ensure the article remainsverifiable and maintains a consistent citation style.Several templates and tools are available to assist in formatting, such asreFill (documentation) andCitation bot (documentation).(August 2022) (Learn how and when to remove this message)

Exception handling syntax is the set of keywords and/or structures provided by a computerprogramming language to allowexception handling, which separates the handling of errors that arise during a program's operation from its ordinary processes. Syntax for exception handling varies betweenprogramming languages, partly to cover semantic differences but largely to fit into each language's overallsyntactic 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 atry...[catch...][finally...] block, and errors are created via athrow statement, but there is significant variation in naming and syntax.

Catalogue of exception handling syntaxes

[edit]

Ada

[edit]
Further information:Ada (programming language)
The WikibookAda Programming has a page on the topic of:Exceptions
Exception declarations
Some_Error:exception;
Raising exceptions
raiseSome_Error;raiseSome_Errorwith"Out of memory";-- specific diagnostic message
Exception handling and propagation
withAda.Exceptions,Ada.Text_IO;procedureFooisSome_Error:exception;beginDo_Something_Interesting;exception-- Start of exception handlerswhenConstraint_Error=>...-- Handle constraint errorwhenStorage_Error=>-- Propagate Storage_Error as a different exception with a useful messageraiseSome_Errorwith"Out of memory";whenError:others=>-- Handle all othersAda.Text_IO.Put("Exception: ");Ada.Text_IO.Put_Line(Ada.Exceptions.Exception_Name(Error));Ada.Text_IO.Put_Line(Ada.Exceptions.Exception_Message(Error));endFoo;

Assembly language

[edit]
Further information: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 theSTXIT macro.Digital Equipment CorporationRT11 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.

ATS

[edit]
Further information:ATS (programming language)
exceptionMyExceptionof(string,int)(* exceptions can carry a value *)implementmain0():void=try$raiseMyException("not enough food",2)with|~MyException(s,i)=>begin$extfcall(void,"fprintf",stderr_ref,"%s: %d",s,i);fileref_close(stderr_ref);end

Bash

[edit]
Further information:Bash (Unix shell)
#!/usr/bin/env bash#set -e provides another error mechanismprint_error(){echo"there was an error"}trapprint_errorexit#list signals to traptempfile=`mktemp`trap"rm$tempfile"exit./other.sh||echowarning:otherfailedechooops)echoneverprinted

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

trap'echo Error at line ${LINENO}'ERR

BASIC

[edit]
Further information:BASIC

AnOn 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 ERRORGOTOhandlerOPEN"Somefile.txt"FORINPUTAS#1CLOSE#1PRINT"File opened successfully"ENDhandler:PRINT"File does not exist"END' RESUME may be used instead which returns control to original position.

C

[edit]
Further information:C (programming language)

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 usesetjmp/longjmp functions:

#include<setjmp.h>#include<stdio.h>#include<stdlib.h>enum{SOME_EXCEPTION=1}exception;jmp_bufstate;intmain(void){if(!setjmp(state))// try{if(/* something happened */){exception=SOME_EXCEPTION;longjmp(state,0);// throw SOME_EXCEPTION}}elseswitch(exception){caseSOME_EXCEPTION:// catch SOME_EXCEPTIONputs("SOME_EXCEPTION caught");break;default:// catch ...puts("Some strange exception");}returnEXIT_SUCCESS;}

Microsoft-specific

[edit]
Further information:Microsoft-specific exception handling mechanisms

Two types exist:

  • Structured Exception Handling (SEH)
  • Vectored Exception Handling (VEH, introduced inWindows XP)

Example of SEH in C programming language:

intfilterExpression(EXCEPTION_POINTERS*ep){ep->ContextRecord->Eip+=8;// divide instruction may be encoded from 2 to 8 bytesreturnEXCEPTION_CONTINUE_EXECUTION;}intmain(void){staticintzero;__try{zero=1/zero;__asm{nopnopnopnopnopnopnop}printf("Past the exception.\n");}__except(filterExpression(GetExceptionInformation())){printf("Handler called.\n");}return0;}

C#

[edit]
Further information:C Sharp (programming language)

Atry block must have at least onecatch orfinally clause and at most onefinally clause.

publicstaticvoidMain(){try{// Code that could throw an exception.}catch(HttpExceptionex){// Handles a HttpException. The exception object is stored in "ex".}catch(Exception){// Handles any CLR exception that is not a HttpException.// Since the exception has not been given an identifier, it cannot be referenced.}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.}}

C++

[edit]
Further information:C++
importstd;intmain(){try{// do something (might throw an exception)}catch(conststd::runtime_errore){// handle a runtime_error e}catch(conststd::exception&e){// catches all exceptions as e}catch(...){// catches all thrown types (including primitives or objects that do nit extend exception), not already caught by a catch block before}}

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

ColdFusion Markup Language (CFML)

[edit]
Further information:ColdFusion Markup Language

Script syntax

[edit]
<cfscript>try{//throw CF9+throw(type="TypeOfException",message="Oops",detail="xyz");// alternate throw syntax:throw"Oops";// this equivalent to the "message" value in the above example}catch(anye){writeOutput("Error: "&e.message);rethrow;//CF9+}finally{//CF9+writeOutput("I run even if no error");}</cfscript>

Adobe ColdFusion documentation[2]

Tag syntax

[edit]
<cftry>     code that may cause an exception<cfcatch...><cftry>             First level of exception handling code<cfcatch...>                 Second level of exception handling code</cfcatch><cffinally>                     final code</cffinally></cftry></cfcatch></cftry>

Adobe ColdFusion documentation[3]

Railo-Lucee specific syntax

[edit]
Further information:Railo andLucee

Added to the standard syntax above, CFML dialects ofRailo andLucee allow aretry statement.[4]

This statement returns processing to the start of the priortry block.

CFScript example:

try{// code which could result in an exception}catch(anye){retry;}

Tag-syntax example:

<cftry><!--- code which could result in an exception ---><cfcatch><cfretry></cfcatch></cftry>

D

[edit]
Further information:D (programming language)
importstd.stdio;// for writefln()intmain(){try{// do something that might throw an exception}catch(FooExceptione){// handle exceptions of type FooException}catch(Objecto){// handle any other exceptionswritefln("Unhandled exception: ",o);return1;}return0;}

In D, afinally clause or theresource acquisition is initialization technique can be used to clean up resources in exceptional situations.

Delphi

[edit]
Further information:Delphi (programming language)
Exception declarations
typeECustom=class(Exception)// Exceptions are children of the class Exception.privateFCustomData:SomeType;// Exceptions may have custom extensions.publicconstructorCreateCustom(Data:SomeType);// Needs an implementationpropertyCustomData:SomeTypereadFCustomData;end;
Raising exceptions
raiseException.Create('Message');raiseException.CreateFmt('Message with values: %d, %d',[value1,value2]);// See SysUtils.Format() for parameters.raiseECustom.CreateCustom(X);
Exception handling and propagation[5]
try// For finally.try// For except....// Code that may raise an exception.exceptonC:ECustomdobegin...// Handle ECustom....ifPredicate(C.CustomData)then...end;onS:ESomeOtherExceptiondobegin// Propagate as an other exception.raiseEYetAnotherException.Create(S.Message);end;onE:Exceptiondobegin...// 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

[edit]
Further information:Erlang (programming language)
try% some dangerous codecatchthrow:{someError,X}->ok;% handle an exceptionerror:X->ok;% handle another exception_:_->ok% handle all exceptionsafter% clean upend

F#

[edit]
Further information:F_Sharp_(programming_language)

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

For comparison, this is a translation ofthe C# sample above.

trytry()(* Code that could throw an exception. *)with|:?System.Net.WebExceptionasex->()(* 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 ofthe OCaml sample below.

exceptionMyExceptionofstring*int(* exceptions can carry a value *)let_=tryraise(MyException("not enough food",2));printfn"Not reached"with|MyException(s,i)->printf"MyException: %s, %d\n"si|e->(* catch all exceptions *)eprintf"Unexpected exception : %O"e;eprintf"%O"e.StackTrace

Haskell

[edit]
Further information:Haskell (programming language)

Haskell does not have special syntax for exceptions. Instead, atry/catch/finally/etc. interface is provided by functions.

importPreludehiding(catch)importControl.ExceptioninstanceExceptionIntinstanceExceptionDoublemain=docatch(catch(throw(42::Int))(\e->print(0,e::Double)))(\e->print(1,e::Int))

prints

(1,42)

in analogy with this C++

importstd;intmain(){try{throwstatic_cast<int>(42);}catch(doublee){std::println("(0,{})",e);}catch(inte){std::println("(1,{})",e);}}

Another example is

do{-- Statements in which errors might be thrown}`catch`\ex->do{-- Statements that execute in the event of an exception, with 'ex' bound to the exception}

In purely functional code, if only one error condition exists, theMaybe type may be sufficient, and is an instance of Haskell'sMonadclass by default. More complex error propagation can be achieved using theError orErrorT monads, for which similar functionality (using`catch`) is supported.

Java

[edit]
Further information:Java (programming language)
The WikibookJava Programming has a page on the topic of:Exceptions

Atry block must have at least onecatch orfinally clause and at most onefinally clause.

try{// Normal execution path.thrownewEmptyStackException();}catch(ExampleExceptionee){// Deal with the ExampleException.}finally{// Always run when leaving the try block (including finally clauses), regardless of whether any exceptions were thrown or whether they were handled.// Cleans up and closes resources acquired in the try block.// May not be run when System.exit() is called and in other system-wide exceptional conditions (e.g. power loss).// Rarely used after try-with-resources was added to the language (see below).}

If multiple resources are acquired, the correct way to deal with them is with nested try blocks.[6] For this reason and others,try-with-resources was added to the language to almost entirely replace finally clauses. Resources acquired in a parentheses after the try keyword will be cleaned up automatically. Classes used in these statements must implement an interface called AutoCloseable.[7]

try(FileReaderfr=newFileReader(path);BufferedReaderbr=newBufferedReader(fr)){// Normal execution path.}catch(IOExceptionioe){// Deal with exception.}// Resources in the try statement are automatically closed afterwards.finally{// A finally clause can be included, and will run after the resources in the try statements are closed.}

JavaScript

[edit]
Further information: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 singlecatch clause, a singlefinally clause, or both.

try{// Statements in which exceptions might be thrownthrownewError("error");}catch(error){// Statements that execute in the event of an exception}finally{// Statements that execute afterward either way}

If there is notry 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(){thrownewError("Example of an error thrown on a 4 second interval.");},4000);

Another interesting quirk is polymorphism: JavaScript can throw primitive values as errors.

try{throw12345;// primitive number}catch(error){console.log(error);// logs 12345 as a primitive number to the console}

Note that thecatch 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 athrow statement inside thecatch statement, or use multiple conditional cases. Let us compare an example in Java and its rough equivalents in JavaScript.

// Example in Javatry{Integeri=null;i.intValue();// throws a NullPointerException}catch(NullPointerExceptionerror){// Variable might be null}catch(ArithmeticExceptionerror){// Handle problems with numbers}
// Approximation #1 in JavaScripttry{// Statements in which exceptions might be thrownvarexample=null;example.toString();}catch(error){if(error.type==="TypeError"){// Variable might be null}elseif(error.type==="RangeError"){// Handle problems with numbers}}
// Approximation #2 in JavaScripttry{try{// Statements in which exceptions might be thrownvarexample=null;example.toString();}catch(error){if(error.type!=="TypeError")throwerror;// Variable might be null}}catch(error){if(error.type!=="RangeError")throwerror;// Handle problems with numbers}

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.

newPromise(function(){thrownewError("Example error!");}).catch(function(err){console.log("Caught ",err);});

Also observe how event handlers can tie into promises as well.

addEventListener("unhandledrejection",function(event){console.log(event.reason);event.preventDefault();//prevent logging the error via console.error to the console--the default behavior});newPromise(function(){thrownewError("Example error!");});

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{// Statements in which exceptions might be thrownconstobj={};obj.selfPropExample=obj;// circular referencethrowobj;}catch(error){// Statements that execute in the event of an exception}

Kotlin

[edit]
Further information:Kotlin (programming language)
try{// Code that may throw an exception}catch(e:SomeException){// Code for handling the exception}

Lisp

[edit]
Further information:Lisp (programming language)

Common Lisp

[edit]
Further information:Common Lisp
(ignore-errors(/10))(handler-case(progn(print"enter an expression")(eval(read)))(error(e)(printe)))(unwind-protect(progn(print"enter an expression")(eval(read)))(print"This print will always be executed, similar to finally."))

Lua

[edit]
Further information:Lua (programming language)

Lua uses thepcall andxpcall functions, withxpcall taking a function to act as acatch block.

Predefined function
functionfoo(x)ifxthenreturnxelseerror"Not a true value"endendfunctionattempt(arg)success,value=pcall(foo,arg)ifnotsuccessthenprint("Error: "..tostring(value))elseprint("Returned: "..tostring(value))endendattempt("hello")-- Returned: helloattempt(nil)-- Error: stdin:5: Not a true valueattempt({})-- Returned: table: 00809308iffoo(42)thenprint"Success"end-- Success
Anonymous function
ifpcall(function()-- Do something that might throw an error.end)thenprint"No errors"-- Executed if the protected call was successful.elseprint"Error encountered"-- Executed if the protected call failed.endprint"Done"-- Will always be executed

Next Generation Shell

[edit]
Further information:Next Generation Shell
Defining custom exception type
typeMyError(Error)
Raising exceptions
throwMyError("this happened")
Exception handling and propagation
try{# something}catch(e:MyError){guarde.val=7# ...}catch(e:MyError){# ...}catch(e:Error){# ...}
Ignoring exceptions - try without catch
try1/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/0tor20# evaluates to 20
"block" - facility to use exceptions to return a value
my_result=blockmy_block{# "block" catches exception thrown by return below# do calculationifcalculation_finished(){my_block.return(42)# throws exception}}

Objective-C

[edit]
Further information:Objective-C
Exception declarations
NSException*exception=[NSExceptionexceptionWithName:@"myException"reason:@"yourReason"userInfo:nil];
Raising exceptions
@throwexception;
Exception handling and propagation
@try{...}@catch(SomeException*se){// Handle a specific exception type....}@catch(NSException*ne){// Handle general exceptions....// Propagate the exception so that it's handled at a higher level.@throw;}@catch(idue){// Catch all thrown objects....}@finally{// Perform cleanup, whether an exception occurred or not....}

OCaml

[edit]
Further information:OCaml
exceptionMyExceptionofstring*int(* exceptions can carry a value *)let_=tryraise(MyException("not enough food",2));print_endline"Not reached"with|MyException(s,i)->Printf.printf"MyException: %s, %d\n"si|e->(* catch all exceptions *)Printf.eprintf"Unexpected exception : %s"(Printexc.to_stringe);(*If using Ocaml >= 3.11, it is possible to also print a backtrace: *)Printexc.print_backtracestderr;(* Needs to beforehand enable backtrace recording with           Printexc.record_backtrace true         or by setting the environment variable OCAMLRUNPARAM="b1"*)

Perl 5

[edit]
Further information:Perl

ThePerl mechanism for exception handling usesdie to throw an exception when wrapped inside aneval{...}; block. After theeval, the special variable$@ contains the value passed fromdie.

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

eval{open(FILE,$file)||dieMyException::File->new($!);while(<FILE>){process_line($_);}close(FILE)||dieMyException::File->new($!);};if($@){# The exception object is in $@if($@->isa('MyException::File')){# Handle file exception}else{# Generic exception handling# or re-throw with 'die $@'}}

The__DIE__ pseudo-signal can be trapped to handle calls todie. 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{__DIE__}=sub{my$err=shift;if($err->isa('MyException')){die$err;# re-throw}else{# Otherwise construct a MyException with $err as a stringdieMyException::Default->new($err);}};

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 theif($@) 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[1] or[2];cf.[3]). But at the cost of not being able to use return values:

eval{# Code that could throw an exception (using 'die') but does NOT use the return statement;1;}ordo{# Handle exception here. The exception string is in $@};

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

  • Error provides a set of exception classes and allows use of the try/throw/catch/finally syntax.
  • TryCatch,Try::Tiny andNice::Try all allow the use of try/catch/finally syntax instead of boilerplate to handle exceptions correctly.
  • Exception::Class is a base class and class-maker for derived exception classes. It provides a full structuredstack trace in$@->trace and$@->trace->as_string.
  • Fatal overloads previously defined functions that return true/false e.g.,open,close,read,write, etc. This allows built-in functions and others to be used as if they threw exceptions.

PHP

[edit]
Further information:PHP
// Exception handling is only available in PHP versions 5 and greater.try{// Code that might throw an exceptionthrownewException('Invalid URL.');}catch(FirstExceptionClass$exception){// Code that handles this exception}catch(SecondExceptionClass$exception){// Code that handles a different exception}finally{// Perform cleanup, whether an exception occurred or not.}

PowerBuilder

[edit]
Further information:PowerBuilder

Exception handling is available in PowerBuilder versions 8.0 and above.

TRY   // Normal execution pathCATCH (ExampleException ee)   //  deal with the ExampleExceptionFINALLY   // This optional section is executed upon termination of any of the try or catch blocks aboveEND TRY

PowerShell

[edit]
Further information:PowerShell

Version 1.0

[edit]
trap[Exception]{# Statements that execute in the event of an exception}# Statements in which exceptions might be thrown

Version 2.0

[edit]
Try{Import-ModuleActiveDirectory}Catch[Exception1]{# Statements that execute in the event of an exception, matching the exception}Catch[Exception2],[Exception3etc]{# Statements that execute in the event of an exception, matching any of the exceptions}Catch{# Statements that execute in the event of an exception, not handled more specifically}

Python

[edit]
Further information:Python (programming language)
f=Nonetry:f=open("aFileName","w")f.write(could_make_error())exceptIOError:print("Unable to open file")except:# catch all exceptionsprint("Unexpected error")else:# executed if no exceptions are raisedprint("File write completed successfully")finally:# clean-up actions, always executediff:f.close()

R

[edit]
Further information:R (programming language)
tryCatch({stop("Here an error is signaled")# default S3-class is simpleError a subclass of errorcat("This and the following lines are not executed because the error is trapped before\n")stop(structure(simpleError("mySpecialError message"),class=c("specialError","error","condition")))},specialError=function(e){cat("catches errors of class specialError\n")},error=function(e){cat("catches the default error\n")},finally={cat("do some cleanup (e.g., setwd)\n")})

Rebol

[edit]
Further information:Rebol
REBOL[Title:"Exception and error handling examples"]; TRY a block; capturing an error! and converting to object!iferror?exception:try[1/0][probedisarmexception]; ATTEMPT results in the value of the block or the value none on errorprintattempt[divide10]; 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 attributessophisticated:func["A function to throw a named error exception"[catch]][throw/namemakeerror!"I'm an error! exception"'moniker]catch/name[sophisticated]'moniker

Rexx

[edit]
Further information:Rexx
signalonhalt;doa=1sayado100000/* a delay */endendhalt:say"The program was stopped by the user"exit

Ruby

[edit]
Further information:Ruby (programming language)
begin# Do something niftyraiseSomeError,"This is the error message!"# Uh-oh!rescueSomeError# This is executed when a SomeError exception# is raisedrescueAnotherError=>error# Here, the exception object is referenced from the# `error' variablerescue# This catches all exceptions derived from StandardErrorretry# This executes the begin section againelse# This is executed only if no exceptions were raisedensure# This is always executed, exception or notend

S-Lang

[edit]
Further information:S-Lang
 try  {    % code that might throw an exception } catch SomeError:  {     % code that handles this exception } catch SomeOtherError: {      % code that handles this exception } finally   % optional block {    % This code will always get executed }

New exceptions may be created using thenew_exception function, e.g.,

 new_exception ("MyIOError", IOError, "My I/O Error");

will create an exception calledMyIOError as a subclass ofIOError. Exceptions may be generated using the throw statement, which can throw arbitraryS-Lang objects.

Smalltalk

[edit]
Further information:Smalltalk
  ["code that might throw an exception" ]on:ExceptionClassdo: [:ex|"code that handles exception" ].

The general mechanism is provided by the messageon:do:.[8] Exceptions are just normal objects that subclassError, you throw one by creating an instance and sending it a#signal message, e.g.,MyExceptionnewsignal. The handling mechanism (#on:do:) is again just a normal message implemented byBlockClosure. The thrown exception is passed as a parameter to the handling block closure, and can be queried, as well as potentially sending#resume to it, to allow execution flow to continue.

Swift

[edit]
Further information:Swift (programming language)

Exception handling is supported since Swift 2.

enumMyException:ErrorType{caseFoo(String,Int)}funcsomeFunc()throws{throwMyException.Foo("not enough food",2)}do{trysomeFunc()print("Not reached")}catchMyException.Foo(lets,leti){print("MyException:\(s),\(i)")}catch{print("Unexpected exception :\(error)")}

Tcl

[edit]
Further information:Tcl
if{[catch{foo}err]}{puts"Error: $err"}

Since Tcl 8.6, there is also a try command:

try{someCommandWithExceptions}onok{resopt}{# handle normal case.}trapListPattern1{erropt}{# handle exceptions with an errorcode matching ListPattern1}trapListPattern2{erropt}{# ...}onerror{erropt}{# handle everything else.}finally{# run whatever commands must run after the try-block.}

VBScript

[edit]
Further information:VBScript
WithNewTry:OnErrorResumeNext'do Something (only one statement recommended).Catch:OnErrorGoTo0:SelectCase.NumberCase0'this line is required when using 'Case Else' clause because of the lack of "Is" keyword in VBScript Case statement'no exceptionCaseSOME_ERRORNUMBER'exception handlingCaseElse'unknown exceptionEndSelect:EndWith' *** Try Class ***ClassTryPrivatemstrDescriptionPrivatemlngHelpContextPrivatemstrHelpFilePrivatemlngNumberPrivatemstrSourcePublicSubCatch()mstrDescription=Err.DescriptionmlngHelpContext=Err.HelpContextmstrHelpFile=Err.HelpFilemlngNumber=Err.NumbermstrSource=Err.SourceEndSubPublicPropertyGetSource()Source=mstrSourceEndPropertyPublicPropertyGetNumber()Number=mlngNumberEndPropertyPublicPropertyGetHelpFile()HelpFile=mstrHelpFileEndPropertyPublicPropertyGetHelpContext()HelpContext=mlngHelpContextEndPropertyPublicPropertyGetDescription()Description=mstrDescriptionEndPropertyEndClass

[9]

Visual Basic 6

[edit]
Further information:Visual Basic

Exception handling syntax is very similar to Basic. Error handling is local on each procedure.

OnErrorGoToHandlerLabel'When error has occurred jumps to HandlerLabel, which is defined anywhere within Function or Sub'orOnErrorGoTo0'switch off error handling. Error causes fatal runtime error and stops application'orOnErrorResumeNext'Object Err is set, but execution continues on next command. You can still use Err object to check error state.'...Err.Raise6' Generate an "Overflow" error using built-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 executedExitSub'exitsprocedure'because we are after Exit Sub statement, next code is hidden for non-error executionHandlerLabel:'defines a common label, here used for exception handling.IfErr.Number=6Then'Select Case statement is typically better solutionResumeFinallyLabel'continue execution on specific label. Typically something with meaning of "Finally" in other languages'orResumeNext'continue execution on statement next to "Err.Raise 6"'orResume'continue execution on (repeat) statement "Err.Raise 6"EndIfMsgBoxErr.Number&" "&Err.Source&" "&Erl&" "&Err.Description&" "&Err.LastDllError'show message box with important error properties'Erl is VB6 built-in line number global variable (if used). Typically is used some kind of IDE Add-In, which labels every code line with number before compilationResumeFinallyLabel

Example of specific (non official) implementation of exception handling, which uses object of class "Try".

WithNewTry:OnErrorResumeNext'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:OnErrorGoTo0:SelectCase.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 built-in Err object)CaseSOME_ERRORNUMBER'exception handlingCaseIs<>0'When Err.Number is zero, no error has occurred'unknown exceptionEndSelect:EndWith' *** Try Class ***PrivatemstrDescriptionAsStringPrivatemlngHelpContextAsLongPrivatemstrHelpFileAsStringPrivatemlngLastDllErrorAsLongPrivatemlngNumberAsLongPrivatemstrSourceAsStringPublicSubCatch()mstrDescription=Err.DescriptionmlngHelpContext=Err.HelpContextmstrHelpFile=Err.HelpFilemlngLastDllError=Err.LastDllErrormlngNumber=Err.NumbermstrSource=Err.SourceEndSubPublicPropertyGetSource()AsStringSource=mstrSourceEndPropertyPublicPropertyGetNumber()AsLongNumber=mlngNumberEndPropertyPublicPropertyGetLastDllError()AsLongLastDllError=mlngLastDllErrorEndPropertyPublicPropertyGetHelpFile()AsStringHelpFile=mstrHelpFileEndPropertyPublicPropertyGetHelpContext()AsLongHelpContext=mlngHelpContextEndPropertyPublicPropertyGetDescription()AsStringDescription=mstrDescriptionEndProperty

[9]

Visual Basic .NET

[edit]
Further information:Visual Basic .NET

ATry block must have at least one clauseCatch orFinally clause and at most oneFinally clause.

Try' code to be executed hereCatchexAsExceptionWhencondition' Handle Exception when a specific condition is true. The exception object is stored in "ex".CatchexAsExceptionType' Handle Exception of a specified type (i.e. DivideByZeroException, OverflowException, etc.)CatchexAsException' 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.EndTry

Visual Prolog

[edit]
Further information:Visual Prolog
try% Block to protectcatchTraceIddo% 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

[10]

X++

[edit]
Further information:Microsoft Dynamics AX
publicstaticvoidMain(Args_args){try{// Code that could throw an exception.}catch(Exception::Error)// Or any other exception type.{// Process the error.}catch{// Process any other exception type not handled previously.}// Code here will execute as long as any exception is caught.}

References

[edit]
  1. ^Bjarne Stroustrup's FAQ
  2. ^"Handling exceptions". Archived fromthe original on 2014-01-02. Retrieved2014-01-01.
  3. ^"Exception handling tags". Archived fromthe original on 2014-01-02. Retrieved2014-01-01.
  4. ^https://issues.jboss.org/browse/RAILO-2176 # JBoss Community issue tracker ticket for addingretry
  5. ^Borland, Delphi Version 7.0, Online help
  6. ^Bloch, Joshua (2018).Effective Java, Third Edition. Addison-Wesley. Item 9, p. 54.ISBN 978-0-13-468599-1
  7. ^"The try-with-resources Statement (The Java™ Tutorials > Essential Java Classes > Exceptions)".
  8. ^"Pharo by Example". Archived fromthe original on 2009-10-21. Retrieved2010-03-20.
  9. ^ab"Try-Catch for VB". Archived fromthe original on 2016-04-16. Retrieved2012-03-17.
  10. ^http://wiki.visual-prolog.com/index.php?title=Language_Reference/Terms#Try-catch-finally

See also

[edit]
Retrieved from "https://en.wikipedia.org/w/index.php?title=Exception_handling_syntax&oldid=1298672873"
Categories:
Hidden categories:

[8]ページ先頭

©2009-2025 Movatter.jp