版主
  
- 积分
- 679
- 金钱
- 679
- 注册时间
- 2013-9-23
- 在线时间
- 95 小时
|
作为一种高级计算机语言,程序在运行的时候需要能够处理人为或者其他原因所带来的异常错误。C语言所提供的是一种函数返回值机制加上if判断语句来处理各种所能预知的异常情况。通常我们知道单片机在出现无效的空间地址访问时会直接转跳至hardfault等异常区域然后停止工作。这种情况看似能够有效保护程序对硬件所带来的危害,而实际上大部分时候我们是不希望系统就这么停止工作了。
UOL语言采用了类似Java的Exception模式。Java的异常机制是将可能与当前异常相关的所有方法路径全部压入栈中,这样用户遍可以轻松获取错误发生的准确地址和原因。然而,单片机的内存资源有限,我们不可能把每次发生的异常都压入栈中。针对这种情况,UOL语言采用了抛出错误代码的机制,只需要用整数值来代替错误信息。用户可以实用throw语句来主动抛出异常,然后用try-catch语句来捕捉throw抛出的异常或者是虚拟机本身所抛出的异常。
例如,下面的代码打算打印字符串对象的长度,由于对象本身为null(空),所以虚拟机会在调用字符串对象时抛出错误并停止工作
输入如下代码
public class Test
{
public static void main()
{
String s=null;//
System.out.printString("start of testing");
System.out.newLine();
//打印字符串对象长度,由于对象s为null,
//所以会引发虚拟机抛出错误而停止工作
System.out.printInt(s.length());
/****以下代码将不会工作****/
System.out.newLine();
System.out.printString("end of testing");
System.out.newLine();
while(true)
{
}
}
}
你将在串口助手中看到如下信息:
其中error code = 14表示null pointer error,可以查看源码errcode.h
当使用try-catch语句时,系统不会因为出现异常而停止工作,只是转跳到catch语句中。这时用户可以按需要自己处理异常。
例如:
public class Test
{
public static void main()
{
//对象必须初始化,这里初始化为null
String s=null;
System.out.printString("start of testing");
System.out.newLine();
try
{
//s为null,虚拟机抛出异常
System.out.printInt(s.length());
}
catch(int e)
{
System.out.printString("error = ");
System.out.printInt(e);
System.out.newLine();
}
/****以下代码将继续工作****/
System.out.newLine();
System.out.printString("end of testing");
System.out.newLine();
while(true)
{
}
}
}
编译运行后,你将在串口助手中看到如下信息:
这次程序不会因为异常而停止工作,你可以看到end of testing。
除了虚拟机抛出异常,其实也可以人为主动抛出异常。只需要判断字符串对象s是否为null来决定是否throw异常。例如:
public class Test
{
public static void main()
{
//对象必须初始化,这里初始化为null
String s=null;
System.out.printString("start of testing");
System.out.newLine();
try
{
//判断如果是null,则主动抛出异常
if(s==null) throw 100;
System.out.printInt(s.length());
}
catch(int e)
{
System.out.printString("error = ");
System.out.printInt(e);
System.out.newLine();
}
/****以下代码将继续工作****/
System.out.newLine();
System.out.printString("end of testing");
System.out.newLine();
while(true)
{
}
}
}
编译运行后可以看到如下信息:
这里我们人为的抛出了值为100的异常信息。
|
|