异常

来源:互联网 发布:vscode debug webpack 编辑:程序博客网 时间:2024/06/04 19:00

课堂练习1

写一个方法void triangle(int a,int b,int c),判断三个参数是否能构成一个三角形。如果不能则抛出异常IllegalArgumentException,显示异常信息:a,b,c “不能构成三角形”;如果可以构成则显示三角形三个边长。在主方法中得到命令行输入的三个整数,调用此方法,并捕获异常。



public class Triangle {
public void triangle(int a,int b,int c) throws Exception{
if(a+b>c&&c-a<a)
{
System.out.println("三条边能构成三角形!");
}
else{
throw new Exception("不能构成三角形!");
}

}
}

import java.util.*;
public class TestTriangle {
public static void main (String args[]) throws Exception{
System.out.println("请输入三角形的三条边为:");
Scanner in=new Scanner(System.in);
int[] a=new int[3];
    a[0]=in.nextInt();
a[1]=in.nextInt();
a[2]=in.nextInt();
try{
Arrays.sort(a);
Triangle triangle=new Triangle();
triangle.triangle(a[0], a[1], a[2]);
}catch(IllegalArgumentException e){
System.err.println("不能构成三角形!");
e.printStackTrace();
}


}
}










课堂练习2

从命令行输入5个整数,放入一整型数组,然后打印输出。要求:

如果输入数据不为整数,要捕获输入不匹配异常,显示“请输入整数”;如果输入数据多余5个,捕获数组越界异常,显示“请输入5个整数”。

无论是否发生异常,都输出“感谢使用本程序!

import java.util.*;


 class Main {
public static void main(String args[]) throws Exception{
int a[]=new int[5] ;
System.out.println("请输入5个整数:");
   Scanner in=new Scanner(System.in);
try{

for (int i = 0; i < 5; i++) {
a[i] = in.nextInt();
}
 
System.out.println("打印结果如下:");
for(int i=0;i<5;i++)
System.out.printf("%3d\n",a[i]);


}


  }catch(InputMismatchException ie){
System.err.println("输入数据必须为整数");
ie.printStackTrace();
}catch(ArrayIndexOutOfBoundsException e){
System.err.println("请输入5个整数");
e.printStackTrace();
}finally{
System.out.println("感谢使用本程序!");
}
   


}
}




总结:

学习了异类这一节知道了异常是在程序运行过程中可能出现的错误,会使正在运行的程序中断。异常处理可以利用try,catch,finally,throw,throws来实现。

将可能出现的异常放在try部分,当try部分的某个方法调用发生异常后,try部分将立刻结束执行,转向执行相应的catch部分;thrw用来手动抛出异常;

throws用来声明异常,用在声明方法时。还知道了一些常见的异常类型。如:ArrayIndexOutOfBoundsException:数组下标越界等等。通过做练习题,对这些知识有了进一步了解,但对异常和异常类型的使用还有待加强。


原创粉丝点击