java中的异常调用(一)

来源:互联网 发布:java命名规则 编辑:程序博客网 时间:2024/04/29 23:08

抽时间写的,随时验证改正

简单来说,就是跟着来。

首先,没有异常时的一个例子。

class CeShi

{

int div(int a,int b)

{

int a ;

int b ;

int c ;

c = a/b;

return c;

}

}

class Demo

{

public static void main(String[] args)

{

System.out.println(div(4,2));

}

}

当然传值还是正确的值。

再次,就开始异常调用了。

方法一,用try ...catch ....finally

class CeShi

{

int div(int a,int b)

{

int a ;

int b ;

int c ;

c = a/b;

return c;

}

}

class Demo

{

public static void main(String[] args)

{

try

{

System.out.println(div(4,2));

}

catch(Exception e)

{

System.out.println("这个是自己输出的异常提示");

System.out.println("这个是Exception的异常提示:"+e.toString());

}

finally

{

System.out.println("这个是只要写了,就一定会执行的语句了。");

}

}

}

方法二,在函数名上用throws 抛出,抛给虚拟机。(异常要么处理,要么抛出,总不能啥都不动对吧)

class CeShi

{

int div(int a,int b)

{

int a ;

int b ;

int c ;

c = a/b;

return c;

}

}

class Demo

{

public static void main(String[] args) throws Exception

{

System.out.println(div(4,2));

}

}


0 0