发布时间 : 星期三 文章java异常练习更新完毕开始阅读4d2f83fb770bf78a65295409
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; } }