Sintaxe de tratamento de exceções - Exception handling syntax

A sintaxe de tratamento de exceções é o conjunto de palavras-chave e / ou estruturas fornecidas por uma linguagem de programação de computador para permitir o tratamento de exceções , que separa o tratamento de erros que surgem durante a operação de um programa de seus processos comuns. A sintaxe para tratamento de exceções varia entre as linguagens de programação , em parte para cobrir diferenças semânticas, mas principalmente para se ajustar à estrutura sintática geral de cada linguagem . Algumas linguagens não chamam o conceito relevante de " tratamento de exceções "; outros podem não ter instalações diretas para isso, mas ainda podem fornecer meios para implementá-lo.

Mais comumente, o tratamento de erros usa um try...[catch...][finally...]bloco e os erros são criados por meio de uma throwinstrução, mas há uma variação significativa na nomenclatura e na sintaxe.

Catálogo de sintaxes de tratamento de exceção

Ada

Declarações de exceção
Some_Error : exception;
Levantando exceções
raise Some_Error;

raise Some_Error with "Out of memory"; -- specific diagnostic message
Tratamento e propagação de exceções
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("Exception: ");
    Ada.Text_IO.Put_Line(Ada.Exceptions.Exception_Name(Error));
    Ada.Text_IO.Put_Line(Ada.Exceptions.Exception_Message(Error));
end Foo;

Linguagem de montagem

A maioria das linguagens assembly terá uma macro instrução ou um endereço de interrupção disponível para o sistema em particular para interceptar eventos como códigos operacionais ilegais, verificação de programa, erros de dados, estouro, divisão por zero e outros semelhantes. Os mainframes IBM e Univac tinham a macro STXIT . Os sistemas da Digital Equipment Corporation RT11 tinham vetores de interceptação para erros de programa, interrupções de E / S e outros. O DOS tem certos endereços de interrupção. O Microsoft Windows tem chamadas de módulo específicas para interceptar erros de programa.

Bash

#!/usr/bin/env bash
#set -e provides another error mechanism
print_error(){
	echo "there was an error"
}
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

Pode-se definir uma armadilha para vários erros, respondendo a qualquer sinal com sintaxe como:

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

BASIC

Uma estrutura On Error goto / gosub é usada em BASIC e é bem diferente do tratamento de exceções moderno; no BASIC, há apenas um manipulador global, enquanto no tratamento de exceções moderno, os manipuladores de exceção são empilhados.

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

C não fornece suporte direto para o tratamento de exceções: é responsabilidade do programador evitar erros em primeiro lugar e testar os valores de retorno das funções.

Em qualquer caso, uma maneira possível de implementar o tratamento de exceções no padrão C é usar as funções setjmp / longjmp :

#include <setjmp.h>
#include <stdio.h>
#include <stdlib.h>

enum { SOME_EXCEPTION = 1 } exception;
jmp_buf state;

int main(void)
{
  if (!setjmp(state))                      // try
  {
    if (/* something happened */)
    {
      exception = SOME_EXCEPTION;
      longjmp(state, 0);                  // throw SOME_EXCEPTION
    }
  } 
  else switch(exception)
  {             
    case SOME_EXCEPTION:                  // catch SOME_EXCEPTION
      puts("SOME_EXCEPTION caught");
      break;
    default:                              // catch ...
      puts("Some strange exception");
  }
  return EXIT_SUCCESS;
}

Específico da Microsoft

Existem dois tipos:

  • Tratamento estruturado de exceções (SEH)
  • Manipulação de exceções vetorizadas (VEH, introduzida no Windows XP )

Exemplo de SEH na linguagem de programação C:

int filterExpression (EXCEPTION_POINTERS* ep) {
   ep->ContextRecord->Eip += 8; // divide instruction may be encoded from 2 to 8 bytes
   return EXCEPTION_CONTINUE_EXECUTION;
}
int main(void) {
   static int zero;
   __try {
       zero = 1/zero;
       __asm {
         nop
         nop
         nop
         nop
         nop
         nop
         nop
       }
       printf ("Past the exception.\n");
   } __except (filterExpression (GetExceptionInformation())) {
       printf ("Handler called.\n");
   }
   return 0;
}

C #

Um trybloco deve ter pelo menos uma cláusula catchor finallye no máximo uma finallycláusula.

public static void Main()
{
    try
    {
        // Code that could throw an exception.
    }
    catch (HttpException ex)
    {
        // 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 ++

#include <exception>
int main() {
   try {
       // do something (might throw an exception)
   }
   catch (const std::exception& e) {
        // handle exception e
   }
   catch (...) {
        // catches all exceptions, not already caught by a catch block before
        // can be used to catch exception of unknown or irrelevant type
   }
}

Em C ++, uma aquisição de recurso é uma técnica de inicialização que pode ser usada para limpar recursos em situações excepcionais. C ++ intencionalmente não oferece suporte finally. Os colchetes externos para o método são opcionais.

ColdFusion Markup Language (CFML)

Sintaxe do script

<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 (any e) {
	writeOutput("Error: " & e.message);
	rethrow; //CF9+
} finally { //CF9+
	writeOutput("I run even if no error");
}
</cfscript>

Documentação do Adobe ColdFusion

Sintaxe de tag

<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>

Documentação do Adobe ColdFusion

Sintaxe específica de Railo-Lucee

Adicionado à sintaxe padrão acima, os dialetos CFML de Railo e Lucee permitem uma retrydeclaração.

Esta instrução retorna o processamento ao início do trybloco anterior .

Exemplo de CFScript:

try {
	// code which could result in an exception 

} catch (any e){
	retry;
}

Exemplo de sintaxe de tag:

<cftry>

	<!--- code which could result in an exception --->

	<cfcatch>
		<cfretry>
	</cfcatch>
</cftry>

D

import std.stdio; // for writefln()
int main() {
  try {
      // do something that might throw an exception
  }
  catch (FooException e) {
       // handle exceptions of type FooException
  }
  catch (Object o) {
       // handle any other exceptions
       writefln("Unhandled exception: ", o);
       return 1;
  }
  return 0;
}

Em D, uma finallycláusula ou a aquisição de recurso é técnica de inicialização pode ser usada para limpar recursos em situações excepcionais.

Delphi

Declarações de exceção
type 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;
Levantando exceções
raise Exception.Create('Message');

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

raise ECustom.CreateCustom(X);
Tratamento e propagação de exceções
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 code
catch
  throw:{someError, X} -> ok;    % handle an exception
  error:X -> ok;                 % handle another exception
  _:_ -> ok                      % handle all exceptions
after
  % clean up
end

F #

Além do baseado em OCaml try...with, F # também tem a try...finallyconstrução separada , que tem o mesmo comportamento de um bloco try com uma finallycláusula em outras linguagens .NET.

Para comparação, esta é uma tradução do exemplo C # acima .

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.
    *)

Para comparação, esta é a tradução da amostra OCaml abaixo .

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 não possui sintaxe especial para exceções. Em vez disso, a try/ catch/ finally/ etc. interface é fornecida por funções.

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

estampas

(1,42)

em analogia com este C ++

#include <iostream>
using namespace std;
int main()
{
  try
    {throw (int)42;}
  catch(double e)
    {cout << "(0," << e << ")" << endl;}
  catch(int e)
    {cout << "(1," << e << ")" << endl;}
}

Outro exemplo é

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
}

Em código puramente funcional, se houver apenas uma condição de erro, o Maybetipo pode ser suficiente e é uma instância da Monad classe de Haskell por padrão. Uma propagação de erro mais complexa pode ser alcançada usando as mônadas Errorou ErrorT, para as quais uma funcionalidade semelhante (usando ) é suportada. `catch`

Java

Um trybloco deve ter pelo menos uma cláusula catchor finallye no máximo uma finallycláusula.

try {
    // Normal execution path.
    throw new EmptyStackException();
} catch (ExampleException ee) {
    // 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.
    // Often used to clean up and close resources such a file handles.
    // May no be run when System.exit() is called and in other system-wide exceptional conditions (e.g. power loss).
}

JavaScript

O design do JavaScript torna os erros altos / difíceis muito incomuns. Erros suaves / silenciosos são muito mais prevalentes. Os erros graves se propagam para a tryinstrução mais próxima , que deve ser seguida por uma única catchcláusula, uma única finallycláusula ou ambas.

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

Se não houver nenhuma trydeclaração, a página da Web não trava. Em vez disso, um erro é registrado no console e a pilha é limpa. No entanto, o JavaScript tem a peculiaridade interessante de pontos de entrada invocados externamente assíncronos. Enquanto, na maioria das outras linguagens, sempre há alguma parte do código em execução o tempo todo, o JavaScript não precisa ser executado linearmente do início ao fim. Por exemplo, ouvintes de eventos, promessas e cronômetros podem ser chamados pelo navegador posteriormente e executados em um contexto isolado, mas compartilhado com o restante do código. Observe como o código abaixo irá gerar um novo erro a cada 4 segundos por um período indefinido de tempo ou até que o navegador / guia / computador seja fechado.

setInterval(function() {
  throw new Error("Example of an error thrown on a 4 second interval.");
}, 4000);

Outra peculiaridade interessante é o polimorfismo: o JavaScript pode lançar valores primitivos como erros.

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

Observe que a catchcláusula é abrangente, que captura todo tipo de erro. Não há nenhuma habilidade sintática para atribuir diferentes manipuladores a diferentes tipos de erro além das extensões Gecko experimentais e atualmente removidas de muitos anos atrás. Em vez disso, pode-se propagar o erro usando uma throwinstrução dentro da catchinstrução ou usar vários casos condicionais. Vamos comparar um exemplo em Java e seus equivalentes aproximados em JavaScript.

// Example in Java
try {
  Integer i = null;
  i.intValue(); // throws a NullPointerException
} catch(NullPointerException error) {
  // Variable might be null
} catch(ArithmeticException error) {
  // Handle problems with numbers
}
// Approximation #1 in JavaScript
try {
  // Statements in which exceptions might be thrown
  var example = null;
  example.toString();
} catch(error) {
  if (error.type === "TypeError") {
    // Variable might be null
  } else if (error.type === "RangeError") {
    // Handle problems with numbers
  }
}
// Approximation #2 in JavaScript
try {
  try {
    // Statements in which exceptions might be thrown
    var example = null;
    example.toString();
  } catch(error) {
    if (error.type !== "TypeError") throw error;
    // Variable might be null
  }
} catch(error) {
  if (error.type !== "RangeError") throw error;
  // Handle problems with numbers
}

Outro aspecto das exceções são as promessas, que tratam a exceção de maneira assíncrona. Tratar a exceção de forma assíncrona tem a vantagem de que os erros dentro do manipulador de erros não se propagam mais para fora.

new Promise(function() {
	throw new Error("Example error!");
}).catch(function(err) {
	console.log("Caught ", err);
});

Observe também como os manipuladores de eventos também podem vincular-se a promessas.

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

new Promise(function() {
  throw new Error("Example error!");
});

Por último, observe que, como o JavaScript usa a coleta de lixo marcar e varrer, nunca há vazamento de memória das instruções de lançamento porque o navegador limpa automaticamente os objetos mortos - mesmo com referências circulares.

try {
  // Statements in which exceptions might be thrown
  const obj = {};
  obj.selfPropExample = obj; // circular reference
  throw obj;
} catch(error) {
  // Statements that execute in the event of an exception
}

Lisp

Lisp Comum

(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 usa as funções pcalle xpcall, xpcallassumindo uma função para atuar como um catchbloco.

Função predefinida
function foo(x)
  if x then 
    return x
  else
    error "Not a true value"
  end
end

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

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

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
Função anônima
if 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

Shell de próxima geração

Definindo o tipo de exceção personalizado
type MyError(Error)
Levantando exceções
throw MyError("this happened")
Tratamento e propagação de exceções
try {
  # something
} catch(e:MyError) {
  guard e.val = 7
  # ...
} catch(e:MyError) {
  # ...
} catch(e:Error) {
  # ...
}
Ignorando exceções - tente sem pegar
try 1/0  # evaluates to null
Ignorando exceções - operador "tor"

"tor" é o operador try-or. Caso haja alguma exceção ao avaliar o argumento da esquerda, avalia o argumento da direita.

1/0 tor 20  # evaluates to 20
"bloco" - facilidade de usar exceções para retornar um valor
my_result = block my_block {  # "block" catches exception thrown by return below
  # do calculation
  if calculation_finished() {
    my_block.return(42)  # throws exception
  }
}

Objective-C

Declarações de exceção
NSException *exception = [NSException exceptionWithName:@"myException"
                           reason:@"whatever"  userInfo:nil];
Levantando exceções
@throw exception;
Tratamento e propagação de exceções
@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 (id ue) {
    // Catch all thrown objects.
    ...
}
@finally {
    // Perform cleanup, whether an exception occurred or not.
    ...
}

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

O mecanismo Perl para tratamento de exceções usa diepara lançar uma exceção quando empacotado dentro de um bloco. Depois de , a variável especial contém o valor passado de . No entanto, problemas de escopo podem tornar isso muito desagradável: eval { ... };eval$@die

my ($error, $failed);
{
    local $@;
    $failed = not eval {
        # Code that could throw an exception (using 'die')
        open(FILE, $file) || die "Could not open file: $!";
        while (<FILE>) {
            process_line($_);
        }
        close(FILE) || die "Could not close $file: $!";
        return 1;
    };
    $error = $@;
}

if ($failed) {
    warn "got error: $error";
}

O Perl 5.005 adicionou a capacidade de lançar objetos e também cordas. Isso permite uma melhor introspecção e tratamento dos tipos de exceções.

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

O __DIE__pseudo-sinal pode ser capturado para lidar com chamadas para die. Isso não é adequado para tratamento de exceções, pois é global. No entanto, ele pode ser usado para converter exceções baseadas em strings de pacotes de terceiros em objetos.

local $SIG{__DIE__} = sub {
    my $err = shift;
    if ($err->isa('MyException')) {
        die $err; # re-throw
    } else {
        # Otherwise construct a MyException with $err as a string
        die MyException::Default->new($err);
    }
};

Os formulários mostrados acima às vezes podem falhar se a variável global $@for alterada entre o momento em que a exceção é lançada e quando ela é verificada na instrução. Isso pode acontecer em ambientes multithread ou até mesmo em ambientes single-threaded quando outro código (normalmente chamado na destruição de algum objeto) redefine a variável global antes do código de verificação. O exemplo a seguir mostra uma forma de evitar este problema (ver [1] ou [2] ; cf . [3] ). Mas ao custo de não ser capaz de usar valores de retorno: if ($@)

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

Vários módulos na Comprehensive Perl Archive Network ( CPAN ) expandem o mecanismo básico:

  • Error fornece um conjunto de classes de exceção e permite o uso da sintaxe try / throw / catch / finally.
  • TryCatche ambos permitem o uso da sintaxe try / catch / finally em vez de clichê para lidar com as exceções corretamente.Try::Tiny
  • Exception::Classé uma classe base e criador de classes para classes de exceção derivadas. Ele fornece um rastreamento de pilha totalmente estruturado em e .$@->trace$@->trace->as_string
  • Fatalsobrecargas funções que retornam verdadeiro falso eg /, previamente definido open, close, read, write, etc. Isto permite funções internas e outros para ser usado como se eles jogaram exceções.

PHP

// Exception handling is only available in PHP versions 5 and greater.
try {
    // Code that might throw an exception
    throw new Exception('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

O tratamento de exceções está disponível no PowerBuilder versões 8.0 e superiores.

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

Versão 1.0

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

Versão 2.0

Try {
    Import-Module ActiveDirectory
    }
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
    }

Pitão

f = None
try:
    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({
   stop("Here an error is signaled")   # default S3-class is simpleError a subclass of error
   cat("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

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 error
print 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

Rubi

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

Gíria

 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
 }

Novas exceções podem ser criadas usando a new_exceptionfunção, por exemplo,

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

criará uma exceção chamada MyIOErrorcomo uma subclasse de IOError. Exceções podem ser geradas usando a instrução throw, que pode lançar objetos S-Lang arbitrários .

Conversa fiada

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

O mecanismo geral é fornecido pela mensagem . As exceções são apenas objetos normais que subclasse , você lança um criando uma instância e enviando uma mensagem, por exemplo ,. O mecanismo de tratamento ( ) é novamente apenas uma mensagem normal implementada por . A exceção lançada é passada como um parâmetro para o fechamento do bloco de tratamento e pode ser consultada, bem como potencialmente enviada a ele, para permitir que o fluxo de execução continue. on:do:Error#signalMyException new signal#on:do:BlockClosure#resume

Rápido

O tratamento de exceções é suportado desde o Swift 2.

enum MyException : ErrorType {
  case Foo(String, Int)
}
func someFunc() throws {
  throw MyException.Foo("not enough food", 2)
}
do {
  try someFunc()
  print("Not reached")
} catch MyException.Foo(let s, let i) {
  print("MyException: \(s), \(i)")
} catch {
  print("Unexpected exception : \(error)")
}

Tcl

if { [ catch {
    foo
} err ] } {
    puts "Error: $err"
}

Desde Tcl 8.6, também existe um comando try:

try {
    someCommandWithExceptions
} on ok {res opt} {
    # handle normal case.
} trap ListPattern1 {err opt} {
    # handle exceptions with an errorcode matching ListPattern1
} trap ListPattern2 {err opt} {
    # ...
} on error {err opt} {
    # handle everything else.
} finally {
    # run whatever commands must run after the try-block.
}

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 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

A sintaxe de tratamento de exceções é muito semelhante à Basic. O tratamento de erros é local em cada procedimento.

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 (non official emulation of Finally section from other languages)
    '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 (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 compilation
Resume FinallyLabel

Exemplo de implementação específica (não oficial) de tratamento de exceções, que utiliza o objeto da classe "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 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

Um Trybloco deve ter pelo menos uma cláusula Catchou Finallycláusula e no máximo uma Finallycláusula.

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 (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

http://wiki.visual-prolog.com/index.php?title=Language_Reference/Terms#Experimente-catch-finally

try
    % 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(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.
}

Referências

Veja também