异常处理是个很重要的概念,很多语言中都对异常处理下了很大的功夫。如果你的语法没有写错,编译器是不会报错,而且编译成功。如果编译成功后,运行时发生了错误该怎么处理呢?例如我要加载一个类,而这个类被删了。这种情况就是异常。我们采用try……catch……finally语句作为处理方式。举个异常处理的例子吧。
实践:
public class testexceptions { public static void main(string[] args) { for ( int i = 0; true; i++ ) { system.out.println("args[" + i + "] is '" + args[i] + "'"); } }} |
在这里面main方法的参数args是个字符串型的数组,在执行的时候要输入java testexceptions 100jq 后面的就是参数args[0]就是第一个参数。我们输入java testexception是出现了错误。如图20-1所示,

这上说的是数组边界溢出异常,第0个产生错误,因为根本就没有args[0],这个元素。
我们再敲一下java testexceptions 100jq 如图20-2所示,

输出了args[0]没有异常了,并且输出了。而循环到i=1时,又发生异常。我们再输入两个参数java testexceptions chinaitlab www.chinaitlab.com 这回两个参数了。同样的道理,args[2]发生异常。
那么我们如何来捕捉这个异常呢,我们对上述代码做一下简单的修改。
实践:
public class testexceptions1 { public static void main(string[] args) { try { for ( int i = 0; true; i++ ) { system.out.println("args[" + i + "] is '" + args[i] + "'"); } } catch (arrayindexoutofboundsexception e) { system.out.println("异常捕捉: " + e); system.out.println("退出..."); } }} |
这回输入刚才那两个参数的话,就不会出现那一堆难懂的英文了。异常已经在我们的掌控之中。否则,有很多异常是足够使内存导毁的。
这里面我们只使用了try…catch 哪个地方你觉得它有毛病,你就try哪。但是try然后,要catch(捕捉)的。如果事先你想不出它会发生什么异常的话,就用finally.
实践:
class finallydemo { static void proca() { try { system.out.println("inside proca"); throw new runtimeexception("demo"); } finally { system.out.println("proca's finally"); } } // 从try程序块内返回 static void procb() { try { system.out.println("inside procb"); return; } finally { //结束 system.out.println("procb's finally"); } } // 执行一个try程序块 static void procc() { try { system.out.println("inside procc"); } finally { system.out.println("procc's finally"); } } public static void main(string args[]) { try { proca(); } catch (exception e) { system.out.println("异常捕捉"); } procb(); procc(); } } |
上述源码打包下载
如果将方法里抛出异常抛出,使用throws关键字 public void abc() throws exception 也是要用catch来捕捉的。
实践:
class throwdemo { static void demoproc() { try { throw new nullpointerexception("demo"); } catch(nullpointerexception e) { system.out.println("caught inside demoproc."); throw e; //重新抛出异常 }} public static void main(string args[]) { try { demoproc(); } catch(nullpointerexception e) { system.out.println("recaught: " + e); }}} |
19个源码打包下载
异常类除了jdk提供我们的那些之外,我们自己还可以自定义的。jdk提供的刚才我们已经见过几个了 arrayindexoutofboundsexception(数组边界溢出),nullpointerexception(空指针异常)。要是jdk没有的,我们只有自己定义了。比如说我们现在要用xml开发,那么jdk没有写这方面的异常类,我们就得自己写一个关于xml的异常了。我们下节课讲自定义异常类。
闽公网安备 35060202000074号