Golang
// 断言
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestSomething(t *testing.T) {
assert := assert.New(t)
assert.Equal(1, 2, "错误信息")
}
// 异常
defer func() {
if err := recover(); err != nil {
fmt.Println(err)
}
}()
panic("抛出异常")
Nodejs
// 断言
const assert = require("assert");
assert(1>2, '错误信息');
// 异常
try {
throw new Error('抛出异常');
} catch (err) {
console.log(err.code, err.message);
} finally {
console.log('最终执行')
}
Python
// 断言
assert(1>2)
// 异常
try:
raise Exception('抛出异常')
pass
except KeyError:
print('字典关键字不存在')
pass
except IndexError:
print('索引超出序列范围')
pass
except TypeError:
print('不同类型数据之间的无效操作')
pass
except (AttributeError, NameError):
print('对象属性不存在时')
print('访问未声明的变量')
pass
except Exception as err:
print(err)
else:
print('没有异常')
pass
finally:
print("最终执行")
C#
// 断言
// 只有在debug模式下才生效
System.Diagnostics.Debug.Assert(1 > 2);
// 异常
try {
throw new Exception("抛出异常");
}
catch (Exception e) {
Console.WriteLine(e.Message);
Console.WriteLine(e.StackTrace.Trim());
}
finally {
Console.WriteLine("最终执行");
}