当前位置:网站首页>实验八 异常处理
实验八 异常处理
2022-07-06 09:22:00 【文文喜欢郭子吖】
实验八 异常处理
实验目的
- 了解异常的概念和异常处理机制
- 掌握捕捉异常的方法
- 掌握创建自定义异常
实验学时 2学时
实验内容
1.编写一个程序,要求从键盘输入一个圆的半径(double类型),计算并输出圆的面积。在没有加入异常处理机制时,输入的数据不是double型数据(如字符串“abc”)会产生什么结果?加入异常处理机制后,让程序在输入不正确的类型数据时给出错误提示并要求重新输入。
package code81;
import java.util.InputMismatchException; //导入输入不匹配异常
import java.util.Scanner;
public class code81 {
public static void main(String[] args) {
// TODO 自动生成的方法存根
input:
while(true) { //循环输入
try { //选定捕获异常的范围
Scanner in = new Scanner(System.in);
double r,area;
System.out.println("请输入圆的半径:");
r=in.nextDouble();
area=r*r*3.14;
System.out.println("圆的面积为:"+area);
}catch(InputMismatchException e) { //处理输入不匹配异常
System.out.println("输入的数据不符合要求!");
System.out.println("请重新输入");
e.printStackTrace(); //在命令行打印异常信息在程序中出错的位置及原因
continue input; //持续输入,确保输入的数据正确
}
}
}
}
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);
}
}
- 可能会产生输入的数据不匹配异常、除0异常、数组越界异常;
package code82;
import java.util.Scanner;
import java.util.InputMismatchException; //导入输入不匹配异常
public class ExceptionSample1 {
public static void main(String[] args) {
// TODO 自动生成的方法存根
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++) {
try { //选定捕获异常的范围
a[i]=sc.nextInt();
sum=sum+a[i];
average=(float)sum/n;
System.out.println(average);
}catch(InputMismatchException e) { //处理输入不匹配异常
System.out.println("输入的数据格式不符合要求!");
}catch(ArithmeticException e) { //处理除0异常
System.out.println("除0异常!");
}catch(ArrayIndexOutOfBoundsException e) { //处理数组越界异常
System.out.println("数组越界异常!");
}
}
}
}
2.修改代码:不管程序在执行过程中会不会产生异常,最后都输出“程序运行结束”
package code82;
import java.util.Scanner;
import java.util.InputMismatchException; //导入输入不匹配异常
public class ExceptionSample2 {
public static void main(String[] args) {
// TODO 自动生成的方法存根
Scanner sc=new Scanner(System.in);
int a[]=new int[5];
int n,sum=0;
int average;
try { //选定捕获异常的范围
n=sc.nextInt();
for(int i=0;i<n;i++) {
a[i]=sc.nextInt();
sum=sum+a[i];
}
average=sum/n;
System.out.println(average);
}catch(InputMismatchException e) { //处理输入不匹配异常
System.out.println("输入的数据格式不符合要求!");
}catch(ArithmeticException e) { //处理除0异常
System.out.println("除0异常!");
}finally { //保证最后程序都按要求输出
System.out.println("程序运行结束!");
}
}
}
3.设计一个程序,输入两个整数和一个算术运算符(+、-、*、/),根据运算符,计算两个整数的运算结果。考虑到用户输入的数据不合法,需要捕获异常(数据格式异常、除零异常、非法运算符异常)。
package code83;
import java.util.Scanner;
import java.util.InputMismatchException; //导入输入不匹配异常
public class Calculate {
public static void main(String[] args) {
// TODO 自动生成的方法存根
Scanner in = new Scanner(System.in);
int a,b;
String c;
try { //选定捕获异常的范围
System.out.println("请输入需要计算的两个整数:");
a=in.nextInt();
b=in.nextInt();
System.out.println("请输入运算符:");
c=in.next();
switch(c) {
case "+":
System.out.println(a + c + b +"="+(a+b));
break;
case "-":
System.out.println(a + c + b +"="+(a-b));
break;
case "*":
System.out.println(a + c + b +"="+(a*b));
break;
case "/":
System.out.println(a + c + b +"="+(a/b));
break;
default:
throw new Exception(); //声明抛弃异常
}
}catch(InputMismatchException e) { //处理数据不匹配异常
System.out.println("数据格式异常!");
}catch(ArithmeticException e) { //处理除0异常
System.out.println("除0异常!");
}catch(Exception e) { //处理default语句中抛弃的非法运算符异常
System.out.println("非法运算符异常!");
}
}
}
4.设计一个程序,根据三角形的三边求三角形面积。要求自定义一个异常类IllegaException,在求面积的方法area()中声明抛出这个异常类型,当从键盘输入三条边的数据不能构成三角形时抛出异常。
package code84;
import java.util.Scanner;
import java.util.InputMismatchException; //导入输入不匹配异常
public class Triangle {
public static double area(int a,int b,int c) throws IllegaException { //构造求三角形面积的方法
if(a+b<=c || a+c<=b || b+c<=a || a<=0 || b<=0 || c<=0) {
throw new IllegaException(); //抛出异常的类型
}
double s=(a+b+c)/2.0;
double area=Math.sqrt(s*(s-a)*(s-b)*(s-c));
return area; //求三角形的面积
}
public static void main(String[] args) throws IllegaException {
// TODO 自动生成的方法存根
Scanner in = new Scanner(System.in);
int a,b,c;
System.out.println("请输入三角形的三边长:");
try { //选定捕获异常的范围
a=in.nextInt();
b=in.nextInt();
c=in.nextInt();
System.out.println("三角形的面积为:"+area(a,b,c)); //调用求面积的方法,输出面积的值
}catch(InputMismatchException e) { //处理输入不匹配异常
System.out.println("输入的数据格式不匹配!");
}
}
}
package code84;
public class IllegaException extends Exception { //自定义异常类IllegaException
IllegaException(){ //构造方法
System.out.println("这样的三边不能构成一个三角形!");
}
}
实验小结
- 使用异常处理比传统的错误管理技术更具优势;
- 使用异常处理可以将错误处理代码与正常代码分离;
- 如果一个方法并不知道如何处理所出现的异常,则可以在声明该方法时声明抛弃该异常;
- 除了运行时异常以外的继承于Exception类的子类都统称为非运行时异常,对于这类异常,Java编译器要求程序必须捕获或者声明抛弃异常;
- 捕获异常:try...catch...finally;
- 不论try语句块中是否有异常发生,finally语句块都会被执行;
- 如果Java提供的系统异常类型不能满足程序设计的需要,就可以设计自己的异常类型。Java推荐用户的异常类型以Exception为直接父类。
边栏推荐
- View UI plus released version 1.3.0, adding space and $imagepreview components
- 4. Binary search
- 魏牌:产品叫好声一片,但为何销量还是受挫
- 3.猜数字游戏
- Leetcode. 3. Longest substring without repeated characters - more than 100% solution
- 【九阳神功】2018复旦大学应用统计真题+解析
- 这次,彻底搞清楚MySQL索引
- Have you encountered ABA problems? Let's talk about the following in detail, how to avoid ABA problems
- . Net6: develop modern 3D industrial software based on WPF (2)
- 抽象类和接口的区别
猜你喜欢
5.MSDN的下载和使用
4. Binary search
A piece of music composed by buzzer (Chengdu)
canvas基础2 - arc - 画弧线
canvas基础1 - 画直线(通俗易懂)
Pit avoidance Guide: Thirteen characteristics of garbage NFT project
Write a program to simulate the traffic lights in real life.
Questions and answers of "basic experiment" in the first semester of the 22nd academic year of Xi'an University of Electronic Science and technology
Caching mechanism of leveldb
Programme de jeu de cartes - confrontation homme - machine
随机推荐
(original) make an electronic clock with LCD1602 display to display the current time on the LCD. The display format is "hour: minute: Second: second". There are four function keys K1 ~ K4, and the fun
3.C语言用代数余子式计算行列式
8. C language - bit operator and displacement operator
甲、乙机之间采用方式 1 双向串行通信,具体要求如下: (1)甲机的 k1 按键可通过串行口控制乙机的 LEDI 点亮、LED2 灭,甲机的 k2 按键控制 乙机的 LED1
String abc = new String(“abc“),到底创建了几个对象
FAQs and answers to the imitation Niuke technology blog project (II)
【手撕代码】单例模式及生产者/消费者模式
Implementation of count (*) in MySQL
Mode 1 two-way serial communication is adopted between machine a and machine B, and the specific requirements are as follows: (1) the K1 key of machine a can control the ledi of machine B to turn on a
Mortal immortal cultivation pointer-2
String ABC = new string ("ABC"), how many objects are created
6. Function recursion
Caching mechanism of leveldb
Mortal immortal cultivation pointer-1
自定义RPC项目——常见问题及详解(注册中心)
[graduation season · advanced technology Er] goodbye, my student days
7. Relationship between array, pointer and array
Set container
Relationship between hashcode() and equals()
Floating point comparison, CMP, tabulation ideas