您的位置:首页 > 其它

异常种类以及处理办法

2010-04-11 12:28 393 查看
1,语法上的错误,导致编译不成功

如:少加分号、大括号等,数据类型不符合或变量没有明确声明就直接使用,会产生语法上的错误而导致编译失败。

2,执行上的错误(java中叫异常事件,Exception),这种错误多半与内存数据的存取有关。

如:数组索引的使用超过了界限、对象强迫转型错误等,这种错误在编译阶段并不会产生,而是运行后会产生,归JVM来管。

3,逻辑上错误,是既不会编译失败,也不会执行失败,但执行的结果却不正确。只有熟悉整个逻辑流程方能发现错误。

异常事件处理注意事项:

如果说try-catch是异常事件的积极处理方式,那么throws就是消极处理方式。

(1)一个try区块可以搭配多个catch区块,但catch的排列有一定规则,这跟catch小括号内的异常类有关系。

倘若各个catch内的异常类有继承关系,则子类要排在前,父类排在后;若没有继承关系,则自由排列。

(2)如果有段程序code不论是否发生异常,都希望被执行,则可以将code放在finally block内,但是finally区块不能单独存在,必须

搭配try-catch使用
package Zero;

public class TryCatchFinally {

public static void main(String[] args) throws ArrayIndexOutOfBoundsException{
try{
String[] bookName={"JAVA Program Design","JSP Program Design"};
System.out.println(bookName[2]);
System.out.println("It is a good book!");

}
catch(ArrayIndexOutOfBoundsException e){
System.out.println("Exception case:The array index is out of the expected boundary!");
}
catch(Exception e){

System.out.println("Exception thing!");

}
finally{
System.out.println("The content of finally block must be running !");
}
System.out.println("The exception case has been resolved.Please continue to run...");
}

}
输出结果:
Exception case:The array index is out of the expected boundary!
The content of finally block must be running !
The exception case has been resolved.Please continue to run...


以上程序说明如下:

一,try区块内发生异常事件

二,比较catch并执行对应的catch内容

三,执行finally

四,执行try-catch-finally架构后的一段程序代码

(3)很大程度上来说,如果自己想处理异常事件,就直接使用try-catch架构,否则就使用throws将异常抛给别人处理!

(4)自定义异常类,就是将自行编写的类继承java函数库内任一异常类即可,并且利用throw自行触发异常事件,JVM才能接受并调用对应的catch区块。如下:

package Zero;

class BookException extends RuntimeException{                                                                                            /*要建立自定义异常就必须先继承函数库内的任一异常类*/
public BookException(String msg){super(msg);}    /*自定义的错误信息必须作为参数值上传至父类的构造函数才算设置完成。*/
}
class Book{
private double price;//=100.0;
public void setPrice(double price) throws BookException{
if(price<100.0||price>1000.0)
throw new BookException("defining setting is error,it cannot set "+price);
else
this.price=price;
}
public double getPrice(){return price;}
}
public class CustomEx {
public static void main(String[] args){
Book book1=new Book();
try{book1.setPrice(99.0);}
catch(BookException e){System.out.println(e);}
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: