java异常练习

2019-03-10 15:24

1、 自己动手编写一个数组越界的异常。 public class Test1{

public static void main(String args[]){

int arr[ ]=new int[5]; arr[10]=7;

System.out.println(“end of main() method !!”); } }

编译时不会产生错误,运行时出现错误信息:

Exception in thread “main” java.lang.ArrayIndexOutOfBoundsException at Test1.main(******) 2、 在练习1的基础上,修改代码,实现如果抛出异常,就输出index out of bound! public class Test2{

public static void main(String args[]){

try{

int arr[ ]=new int[5]; arr[10]=7; }

catch(ArrayIndexOutOfBoundsException e){ System.out.println(“index out of bound!”); } } }

注意:不写catch而直接写finally也能实现。

3、 在练习2的基础上,在catch语句里实现输出异常信息。 public class Test3{

public static void main(String args[]){

try{

int arr[ ]=new int[5]; arr[10]=7; }

catch(ArrayIndexOutOfBoundsException e){ System.out.println(“index out of bound!”); System.out.println(“Exception=”+e);

System.out.println(“Exception=”+e.getMessage()”); System.out.println(“Exception=”+e.toString()”); } } }

蓝色部分均可以实现。

4、 编写代码,做运算a/b,再执行a/b前首先判断b是不是等于零。如果b等于零,抛出数

学异常。

public class Test4{

public static void main(String args[]){

int a=4,b=0;

try{

if(b= =0) throw new ArithmeticException(); else

System.out.println(“result is”+a/b); }catch(ArithmeticException e){ System.out.println(e+” throwed!!”) }

} }

5、 编写代码,再main()方法中调用类CCircle中的方法,计算圆的面积。并且自己定义一

个异常类,如果半径为负值,抛出自己定义的异常。(在类CCircle中判断并抛出异常) class CCircleException extends Exception{} class CCircle{

private double radius;

public void setRadius(double r) throws CCircleException{

if(r<0){

throw new CCircleException(); } else

Radius=r; }

public void show(){

System.out.println(“area=”+3.14*radius*radius); } }

public class Test5{

public static void main(String args[]){ CCircle cir=new CCircle(); try{

cir.setRadius(-2.0); }

catch(CCircleException e){

System.out.println(e+” throwed!!”); }

cir.show; } }


java异常练习.doc 将本文的Word文档下载到电脑 下载失败或者文档不完整,请联系客服人员解决!

下一篇:综合英语2形成系统模拟6

相关阅读
本类排行
× 注册会员免费下载(下载后可以自由复制和排版)

马上注册会员

注:下载文档有可能“只有目录或者内容不全”等情况,请下载之前注意辨别,如果您已付费且无法下载或内容有问题,请联系我们协助你处理。
微信: QQ: