本文实例讲述了Java异常处理原理与用法。分享给大家供大家参考,具体如下:
首发日期:2018-03-26

算术异常类:ArithmeticExecption
空指针异常类:NullPointerException
类型强制转换异常:ClassCastException
数组下标越界异常:ArrayIndexOutOfBoundsException
输入输出异常:IOException



public class Demo {
public static void main(String[] args) {
// int a=10/0;
try{
int a=10/0;
}catch(ArithmeticException e) {
System.out.println("run in ArithmeticException "+e);
//run in ArithmeticException java.lang.ArithmeticException: / by zero
}
catch (Exception e) {
System.out.println(e);
}finally {
System.out.println("最终执行的");//最终执行的
}
}
}
throws用于声明异常,声明函数可能发生的异常。【当函数中有throw来抛出异常时,函数头必须使用throws声明异常】
throw用于手动抛出异常,可以抛出自定义异常信息:throw 异常类型(异常信息)
public class Demo2 {
static int div(int a,int b) throws ArithmeticException{
if (b==0){
throw new ArithmeticException("发生除零异常了!");
}
return a/b;
}
public static void main(String args[]) {
try {
System.out.println(div(2,0));
}catch(ArithmeticException e) {
System.out.println(e.getMessage());//发生除零异常了!
}finally {
System.out.println("in finally");//in finally
}
System.out.println("after finally");//after finally
}
}
一般对于不想在函数中处理异常时,一般采用异常抛出处理(throw throws);否则使用try…catch…finally捕获异常。
有时候没有定义我们想要的异常(比如我们MYSQL连接异常),那么我们可以自定义异常。
class MyException extends Exception{
public MyException() {}
public MyException(String msg) {
super(msg);
}
}
public class Demo3 {
static int div(int a,int b) throws MyException {
if (b==0){
throw new MyException("发生异常了!");
}
return a/b;
}
public static void main(String args[]) {
try {
System.out.println(div(2,0));
}catch(Exception e) {
System.out.println(e);//异常.MyException: 发生除零异常了!
}
}
}
public class Demo {
public static void main(String[] args) {
Boolean food=false;
System.out.println("准备开始吃饭");
assert food;
System.out.println("饭来了");
}
}

更多java相关内容感兴趣的读者可查看本站专题:《Java面向对象程序设计入门与进阶教程》、《Java数据结构与算法教程》、《Java操作DOM节点技巧总结》、《Java文件与目录操作技巧汇总》和《Java缓存操作技巧汇总》
希望本文所述对大家java程序设计有所帮助。