English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
在任何编程语言中,都需要异常处理来处理运行时错误,这样才能保持应用程序的正常流。异常通常会中断应用程序的正常流,这就是为什么我们需要在应用程序中使用异常处理的原因。
通常,当Erlang中发生异常或错误时,将显示以下消息。
{"init terminating in do_boot", {undef,[{helloworld,start,[],[]}, {init,start_it,1,[]},{init,start_em,1,[]}]}}
故障转储将被写入-
erl_crash.dump init terminating in do_boot ()
在Erlang中,有3种例外类型-
Error−调用将终止当前进程的执行,并在捕获到最后一个函数及其参数时包含堆栈跟踪。这些是引发上述运行时错误的异常。erlang:error(Reason)
Exists −有两种Exists : 内部退出和外部退出。内部退出通过调用函数 exit/1来触发,并使当前进程停止执行。外部出口在 exit/2中被调用,并且与 Erlang 的并发方面中的多个进程有关。
Throw −throw是一类异常,用于程序员可以处理的情况。与退出和错误相比,它们并没有带来任何“崩溃过程!”他们背后的意图,而是他们控制的流量。当您在期望程序员处理抛出时使用抛出,通常最好在使用它们的模块中记录它们的使用。
try... catch 是一种计算表达式的方法,同时让您处理成功的案例以及遇到的错误。
try-catch表达式的一般语法如下所示。
try Expression of SuccessfulPattern1 [Guards] -> Expression1; SuccessfulPattern2 [Guards] -> Expression2 catch TypeOfError:ExceptionPattern1 -> Expression3; TypeOfError:ExceptionPattern2 -> Expression4 end
L'expression entre try et of est appelée protégée. Cela signifie que toute exception de type quelconque qui se produit lors de cet appel sera capturée. Les motifs et expressions entre try... et catch sont complètement similaires à ceux de case....
Enfin, la partie catch - ici, vous pouvez remplacer TypeOfError par error, throw ou exit pour chaque type que vous voyez dans ce chapitre. Si aucun type n'est fourni, il est supposé que c'est une exception qui est lancée.
Error | Type d'erreur |
---|---|
badarg | Type de données du paramètre incorrect ou format incorrect. |
badarith | Paramètre incorrect dans l'expression arithmétique. |
{badmatch,V} | L'évaluation de l'expression match a échoué. La valeur V ne correspond pas. |
function_clause | Impossible de trouver la clause correspondante de la fonction lors de l'évaluation d'une appelle de fonction. |
{case_clause,V} | Impossible de trouver la branche correspondante lors du calcul d'une expression case. La valeur V ne correspond pas. |
if_clause | Impossible de trouver la branche réelle lors de l'évaluation d'une expression if. |
{try_clause,V} | Impossible de trouver la branche correspondante lors du calcul d'une section d'expression try. La valeur V ne correspond pas. |
undef | Impossible de trouver la fonction lors de l'évaluation d'une appelle de fonction. |
{badfun,F} | L'amusement F a un problème |
{badarit,F} | Un amusement est appliqué au nombre d'arguments d'erreur. F décrit le plaisir et les disputes. |
timeout_value | La valeur d'attente d'expression receive..after est calculée comme tout autre valeur que l'entier ou l'infini. |
noproc | Essayer de se connecter à un processus inexistant. |
Voici un exemple de comment utiliser ces exceptions et de comment les traiter.
La première fonction génère tous les types d'exceptions possibles.
Ensuite, nous écrivons une fonction enveloppeur pour appeler generate_exception dans une expression try…catch.
-module(helloworld). -compile(export_all). generate_exception(1) -> a; generate_exception(2) -> throw(a); generate_exception(3) -> exit(a); generate_exception(4) -> {'SORTIE', a}; generate_exception(5) -> erlang:error(a). demo1()) -> [catcher(I) || I <- [1,2,3,4,5]]. catcher(N) -> try generate_exception(N) of Val -> {N, normal, Val} attraper lancer:X -> {N, attrapé, lancé, X}; sortie:X -> {N, attrapé, sorti, X}; erreur:X -> {N, attrapé, erreur, X} fin. demo2()) -> [{I, (catch generer_exception(I))} || I <- [1,2,3,4,5]]. demo3()) -> essayer generer_exception(5) attraper erreur:X -> {X, erlang:get_stacktrace()} fin. recherche(N) -> case(N) of 1 -> {'SORTIE', a}; 2 -> sortie(a) fin.
Si nous exécutons le programme HelloWorld:demo()., nous obtenons la sortie suivante
[{1,normal,a}, {2,attrapé,lancé,a}, {3,attrapé,sorti,a}, {4,normal,{'SORTIE',a}}, {5,attrapé,erreur,a}]