---
title: "断言位置的选择：谁犯错谁异常"
author: "arksea"
date: "2010-06-12T14:43:29Z"
tags: ["C", "C#", "C++"]
categories: ["编程语言"]
slug: "untitled"
draft: false
lastmod: "2010-06-12T14:43:29Z"
id: 690553
url: "https://arksea.iteye.com/blog/690553"
---

比如某gen\_server：

```
...

hello(A,B,C) when is_atom(A),is_integer(B),is_binary(C) ->
    gen_server:cast(?SERVER,{hello, A, B, C}).

handle_cast({hello, A, B, C}, State} ->
     ....
     {noreply, State}.

...
```

 

 

     将断言加在hello/3上显然比加在handle\_cast/2上合理。

     如果将断言加在handle\_cast上，调用发起方出错将造成此server无故重启甚至失效，无法为其他进程提供服务，而作为出错的调用方却不受影响。

     将断言加于hello上，调用方将因自己的错误发生异常，从而正确的报告异常或者拥有重启恢复的机会，也不会影响目标服务和其他进程。