实验目的

  1. 了解异常的概念和异常处理机制
  2. 掌握捕捉异常的方法
  3. 掌握创建自定义异常

实验学时 2学时

实验内容

  1. 编写一个程序,要求从键盘输入一个圆的半径(double类型),计算并输出圆的面积。在没有加入异常处理机制时,输入的数据不是double型数据(如字符串“abc”)会产生什么结果?加入异常处理机制后,让程序在输入不正确的类型数据时给出错误提示并要求重新输入。

结果:输入数据格式不匹配 

实现代码:

import java.util.InputMismatchException;

import java.util.Scanner;



public class Test1 {

    public static void main(String[] args) {



        Scanner sc = new Scanner(System.in);



        try {

            double r = sc.nextDouble();

            double s = 3.14 * r * r;

            System.out.println("圆的面积为:" + s);

        } catch (InputMismatchException e) {

            System.out.println("请以正确的形式输出");

        }

    }

}

2.分析下面的程序。

(1)程序在运行时会产生哪些异常?怎样捕获并处理异常?

(2)修改代码:不管程序在执行过程中会不会产生异常,最后都输出“程序运行结束”

import java.util.Scanner;
public class ExceptionSample {
public static void main(String[] args) {
            Scanner sc=new Scanner(System.in);
            int a[]=new int[5];
            int n,sum=0;
            float average;
n=sc.nextInt();
              for(int i=0;i<n;i++){
a[i]=sc.nextInt();
sum=sum+a[i];
              }
average=(float)sum/n;
              System.out.println(average);
          }
}

(1)数组越界异常、输入格式不匹配异常、算数异常。try语句里面存放异常可能发生的地方,catch语句用于捕获cry语句中发生的异常。

(2)修改后代码:  

import java.util.Scanner;

public class Test2 {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		System.out.println("输入n个整数");
		int a[] = new int[5];
		int n, sum = 0;
		float average;
		n = sc.nextInt();
		sc.close();
		try {
			for (int i = 0; i < n; i++) {
				a[i] = sc.nextInt();
				sum = sum + a[i];
			}
			average = (float) sum / n;
			System.out.println(average);
			System.out.println("程序运行结束");
		} catch (Exception e) {
			System.out.println("程序运行结束");
		}
	}
}


3.设计一个程序,输入两个整数和一个算术运算符(+、-、*、/),根据运算符,计算两个整数的运算结果。考虑到用户输入的数据不合法,需要捕获异常(数据格式异常、除零异常、非法运算符异常)。

实现代码:

      

import java.util.InputMismatchException;

import java.util.Scanner;



public class Test3 {

    public static void main(String[] args)  {

        Scanner sc = new Scanner(System.in);

        try {

            System.out.println("请输入两个整数,一个算数运算符(+,-,*,/)");

            int x = sc.nextInt();

            int y = sc.nextInt();

            String str = sc.next();

            String a = "+";

            String b = "-";

            String c = "*";

            String d = "/";

            if (str.equals("+") == true) {

                System.out.println(x + y);

            } else if (str.equals("-") == true) {

                System.out.println(x - y);

            } else if (str.equals("*") == true) {

                System.out.println(x * y);

            } else if (str.equals("/") == true) {

                 

                System.out.println(x / y);

            }else

            {

                throw new positiveException();

            }

            //当异常被引发时,每个catch子句被依次检查,第一个匹配异常类型的子句执行

        } catch (InputMismatchException e) {

            System.out.println("输入的数据格式不匹配!");

        }  //当一个catch子句执行以后,其他的子句将被旁路。

 catch (ArithmeticException e) {

            System.out.println("除数为0!");

        }

        catch(positiveException e)

        {

            System.out.println("非法运算符");

        }

    }

}

 

4.设计一个程序,根据三角形的三边求三角形面积。要求自定义一个异常类IllegaException,在求面积的方法area()中声明抛出这个异常类型,当从键盘输入三条边的数据不能构成三角形时抛出异常。

  运行代码:

          

import java.util.Scanner;



public class Test4 {

    public static void main(String[] args) {

        Scanner sc=new Scanner(System.in);

        System.out.println("输入三角形的三边:");

        int a=sc.nextInt();

        int b=sc.nextInt();

        int c=sc.nextInt();

        sc.close();

        try

        {



            if(a+b<=c||a+c<=b||b+c<=a)

            {

                throw new IllegaException();

            }

            double s=(double)(a+b+c)/2;

            double d=Math.sqrt(s*(s-a)*(s-b)*(s-c));

            System.out.println(d);

        }catch(IllegaException e)

        {

            System.out.println("输入数据不能构成一个三角形");

        }

    }

}//自定义异常

class IllegaException extends Exception{

      public    IllegaException() {//自定义异常的无参构造方法

    super("输入数据不能构成一个三角形");

}

    }