第一范文网 - 专业文章范例文档资料分享平台

java异常练习

来源:用户分享 时间:2025/8/8 2:18:51 本文由loading 分享 下载这篇文档手机版
说明:文章内容仅供预览,部分内容可能不全,需要完整文档或者需要复制内容,请下载word后使用。下载word有问题请添加微信号:xxxxxxx或QQ:xxxxxx 处理(尽可能给您提供完整文档),感谢您的支持与谅解。

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异常练习 的文档
java异常练习.doc 将本文的Word文档下载到电脑,方便复制、编辑、收藏和打印
本文链接:https://www.diyifanwen.net/c30f439t8239nplx1m1vt_1.html(转载请注明文章来源)
热门推荐
Copyright © 2012-2023 第一范文网 版权所有 免责声明 | 联系我们
声明 :本网站尊重并保护知识产权,根据《信息网络传播权保护条例》,如果我们转载的作品侵犯了您的权利,请在一个月内通知我们,我们会及时删除。
客服QQ:xxxxxx 邮箱:xxxxxx@qq.com
渝ICP备2023013149号
Top