---
title: "erlang异常--try...catch"
author: "room_bb"
date: "2016-07-13T19:48:41Z"
tags: []
categories: ["编程语言"]
slug: "erlang-try-catch"
draft: false
lastmod: "2016-07-13T19:48:41Z"
id: 2311080
url: "https://room-bb.iteye.com/blog/2311080"
---

<span style="color:blue">触发异常</span>

```java

throw(Term)
exit(Reason)
erlang:error(Reason)

特列：exit(normal)，进程调用它所跑出的异常不会被捕获，该进程正常终止

```


<span style="color:blue">try...catch</span>

```java

try
    unsafe_fun()
catch
    ErrType:Reason ->
        do_something()
end.

```


<span style="color:blue">try...of...catch</span>

```java

try
    unsafe_fun()
of
    O ->
        io:format("do nothing");
    N ->
        do_something_with(N)
catch
    _:_ ->
        do_something()
end

of...之间的内容，不在try的保护范围

```


<span style="color:blue">try...after</span> 不管try中执行情况如何，after都会执行，这个机制通常用于资源释放

```java

{ok, Fd} = file:open("test.txt", [read]),
try
    do_something_with_file(Fd)
after
    file:close(Fd)
end

```