assert 断言 使用
- 在语句执行过程中,插入asser(bool表达式),来判断异常情况
- 如果表达式值为true,则继续后面的语句,如果值为false,则报异常,会抛出一个AssertionError异常 。
- assert只有在调试模式下生效,生产模式会忽略
assert(...)
import 'dart:convert';
import 'package:shared_preferences/shared_preferences.dart';
extension SharedPreferencesExtension on SharedPreferences {
Future<bool> setJson(String key, Map<String, dynamic> json) {
assert(json != null);
assert(key != null);
var value = jsonEncode(json);
return this.setString(key, value);
}
Map<String, dynamic> getJson(String key) {
assert(key != null);
var value = this.getString(key);
var json = jsonDecode(value);
return json;
}
}
int age = 22
bool result = age < 0
print(result)
assert(result)
print(age)
复制代码
异常处理
- 抛异常 使用 throw xxx 抛一个异常 :throw xxxException();
- 抛任意一个类型 : throw "error"
捕获异常
- try catch finally
- try 包含一个语句块
- on 可以捕获指定一个具体的异常
- catch 可以捕获任意异常
- finally 无论如何都会执行到的语句块
try {
var a = 1/0;
}on IntegerDivisionByZeroException{
print('0 被除');
}on Exception catch(e){
print('a exception: $e');
}catch (e) {
print('exception $e');
}finally {
print('finally');
}