java异常处理例题代码(精)

  • 格式:doc
  • 大小:21.50 KB
  • 文档页数:8

下载文档原格式

  / 13
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

App9_1.java:输出一个数组的所有元素,捕获数组下标越界异常和除娄为0异常。

public class App9_1{

public static void main(String args[]{

int i;

int[] a={1,2,3,4};

for(i=0;i<5;i++

System.out.println(" a["+i+"]="+a[i];

System.out.println("5/0"+(5/0;

}

}

App9_2.java:使用try-catch-finall语句对程序中的异常进行捕获与处理。public class App9_2{

public static void main(String args[]{

int i;

int a[]={1,2,3,4};

for (i=0;i<5;i++{

try{

System.out.print("a["+i+"]/"+i+"="+(a[i]/i;

}

catch(ArrayIndexOutOfBoundsException e{

System.out.print("捕获到了数组下标越界异常";

}

catch(ArithmeticException e{

System.out.print("异常类名称是:"+e; //显示异常信息

catch(Exception e{

System.out.println("捕获"+e.getMessage(+"异常!"; //显示异常信息}

finally{

System.out.println(" finally i="+i;

}

}

System.out.println("继续!!";

}

}

App9_3.java:使用throw语句在方法中抛出异常。

public class App9_3{

public static void main(String args[]{

int a=5,b=0;

try{

if (b==0

throw new ArithmeticException(; //抛出异常,不是必须的

else

System.out.println(a+"/"+b+"="+a/b; //若不抛出异常,则运行此行}

catch(ArithmeticException e{

System.out.println("异常:"+e+"被抛出了!";

e.printStackTrace(; //显示异常信息

}

}

App9_4.java:求阶乘并捕获可能出现的三种异常。

public class App9_4{

public static double multi(int n{

if(n<0

throw new IllegalArgumentException("求负数阶乘异常"; double s=1;

for(int i=1;i<=n;i++ s=s*i;

return s;

}

public static void main(String[] args{

try{

int m=Integer.parseInt(arg[0];

System.out.println(m+"!="+multi(m; //调用方法multi求阶乘。}

catch (ArrayIndexOutOfBoundsException e{

System.out.println("命令行中没提供参数!";

}

catch (NumberFormatException e{

System.out.println("应输入一个整数!";

}

catch (IllegalArgumentException e{

System.out.println("出现的异常是:"+e.toString(;

}

finally{

System.out.println("程序运行结束!";

}

}

}

App9_5.java:判断数字并捕获可能出现的三种异常。

//App9_5.java 使用throws语句在方法之中抛出异常

public class App9_5{

static void check(String str1 throws NullPointerException{ //方法头抛出空指针异常if(str1.length(>2{

str1=null;

System.out.println(str1.length(; //空字符串的长度

}

char ch;

for (int i=0;i

ch=str1.charAt(i;

if (!Character.isDigit(ch //判断参数中字符是否为数字

throw new NumberFormatException(; //方法中抛出数字格式异常

}

}

public static void main(String args[] throws Exception{ //抛出异常给系统处理

int num;

try{

check(args[0];

num=Integer.parseInt(args[0];