Java作业7-Java异常处理

异常处理这块有些不太理解,看看Bz网课-异常 

编程1-计算器输入异常

题目

计算器输入异常

在实验三中实现的命令行计算器已有功能基础上,添加异常处理机制,当用户输入的操作数为非整数时,利用异常处理机制显示错误提示信息。如: 

$java Calculator 5 + 9 
5+9=14 
$java Calculator 5.1 + 9 
Wrong Input first operand: 5.1 
$java Calculator 5 + 9.1 
Wrong Input second operand: 9.1 

计算器👇 

实验三题目4

补充

首先看一下Java parseInt() 方法

看下这条代码↓

public class Test{
    public static void main(String args[]){
        int x =Integer.parseInt("9.1");
        System.out.println(x);
    }
}

这条代码编译是不会报错的

但是运行会出现异常↓

Exception in thread "main" java.lang.NumberFormatException: For input string: "9.1"
	at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:67)
	at java.base/java.lang.Integer.parseInt(Integer.java:662)
	at java.base/java.lang.Integer.parseInt(Integer.java:778)
	at Test.main(Test.java:3)

NumberFormatException即出现了数据类型异常

题目代码

public class Main {
    public static void main(String[] args) {
        
        int num1 = 0;
        int num2 = 0;
        
        // 异常处理用于验证第一个操作数
        try {
            num1 = Integer.parseInt(args[0]);
        } catch (NumberFormatException e) {
            System.out.println("Wrong Input first operand: " + args[0]);
            return;
        }
        
        // 异常处理用于验证第二个操作数
        try {
            num2 = Integer.parseInt(args[2]);
        } catch (NumberFormatException e) {
            System.out.println("Wrong Input second operand: " + args[2]);
            return;
        }
        
        char operator = args[1].charAt(0);
        int result = 0;
        switch (operator) {
            case '+':
                result = num1 + num2;
                System.out.printf("%d + %d = %d%n", num1, num2, result);
                break;
            case '-':
                result = num1 - num2;
                System.out.printf("%d - %d = %d%n", num1, num2, result);
                break;
            case 'x':
                result = num1 * num2;
                System.out.printf("%d x %d = %d%n", num1, num2, result);
                break;
            case '/':
                if (num2 != 0) {
                    if (num1 % num2 == 0) {
                        result = num1 / num2;
                        System.out.printf("%d / %d = %d%n", num1, num2, result);
                    } else {
                        double divisionResult = (double) num1 / num2;
                        System.out.printf("%d / %d = %.2f%n", num1, num2, divisionResult);
                    }
                } else {
                    System.out.println("Cannot divide by zero.");
                }
                break;
            default:
                System.out.println("Invalid operator: " + operator);
                break;
        }
    }
}

补充2,异常的一个例子

多个异常处理
try块中有多行代码,都有可能出现异常信息,程序执行的时候是从上往下执行的,当碰到异常情况的时候就会跳出try块,从而trny块中剩余的代码就不会执行了。

public class Main2{
	public static void main(String[] args) {
		int i = 10;
		String str = null;
		int[] arr = new int[3];
		try {
			System.out.println(i/0);//当出现一个异常时,后面的异常是不会执行的
			System.out.println(str.length());
			arr[10] = 100;
		} catch (ArithmeticException e) {
			System.out.println("除数为0");
		} catch (NullPointerException e) {
			System.out.println("空指针异常");
		} catch (ArrayIndexOutOfBoundsException e) {
			System.out.println("数组下标越界异常");
		}
	}
}
除数为0

补充3

public class Main2{
	public static void main(String[] args) {
		int i = 10;
		String str = null;
		int[] arr = new int[3];
		try {
			System.out.println(i/0);//当出现一个异常时,后面的异常是不会执行的
			System.out.println(str.length());
			arr[10] = 100;
		} catch (Exception e){ //Exception能捕获到上述所有异常,应该把Exception异常这个父类放到最下面
			
		} catch (ArithmeticException e) {
			System.out.println("除数为0");
		} catch (NullPointerException e) {
			System.out.println("空指针异常");
		} catch (ArrayIndexOutOfBoundsException e) {
			System.out.println("数组下标越界异常");
		}
	}
}
Main2.java:12: 错误: 已捕获到异常错误ArithmeticException
		} catch (ArithmeticException e) {
		  ^
Main2.java:14: 错误: 已捕获到异常错误NullPointerException
		} catch (NullPointerException e) {
		  ^
Main2.java:16: 错误: 已捕获到异常错误ArrayIndexOutOfBoundsException
		} catch (ArrayIndexOutOfBoundsException e) {
		  ^
3 个错误

把Exception放到最下面就好了

编程2-抛出异常,捕获异常

题目

定义一个类ThrowExceptionApp,其中包含两个方法f()和g(),其中在g()中,声明为能够抛出自定义异常类型OneException,并在方法实现中抛出此种异常类对象,该异常类的构造方法带一个字符串类型参数,构造实现时调用父类构造方法即可。在f()中,调用g(),捕获g()抛出的异常,并在catch子句中抛出另一个自定义异常类TwoException对象。在main方法中对抛出的异常进行正确处理 

Exception类的构造方法👇

题目代码

首先声明,来自AI

class OneException extends Exception {
    public OneException(String message) {
        super(message);
    }
}

class TwoException extends Exception {
    public TwoException(String message) {
        super(message);
    }
}
public class ThrowExceptionApp {

    public void g() throws OneException {
        throw new OneException("Exception from g()");
    }

    public void f() throws TwoException {
        try {
            g();
        } catch (OneException e) {
            throw new TwoException("Exception thrown from f(), caused by " + e.getMessage());
        }
    }

    public static void main(String[] args) {
        ThrowExceptionApp app = new ThrowExceptionApp();
        try {
            app.f();
        } catch (TwoException e) {
            System.out.println("Caught exception in main: " + e.getMessage());
        }
    }
}
Caught exception in main: Exception thrown from f(), caused by Exception from g()

编程3-十六进制转换异常

题目

自定义一方法int hex2dec(String hStr)实现十六进制字符串到十进制整数的转换。如果输入参数为一非法的十六进制字符串,则抛出 NumberFormatException;自定义一异常类名为 HexFormatException,如果输入参数为非法的十六进制字符串,则抛出该异常类对象;并定义main实现对上述两种异常类型的检测和捕获 

代码 

import java.util.*;

// 定义自定义异常类 HexFormatException
class HexFormatException extends NumberFormatException {
    public HexFormatException(String message) {
        super(message);//沿用父类构造
    }
}
public class Main {
	//十六进制转化为十进制
	public static void main(String[] args) {
		Scanner input = new Scanner( System.in );
		String str = input.nextLine();
		int n=0;	//存储十进制数
		try{
			for ( int i = 0;i < str.length();i++ ){
				n=n*16+Getbit(str.charAt(i));
			}
			System.out.println(n);
		} catch (HexFormatException e) {
			System.out.println(e.getMessage());
		}
	}
	
	public static int Getbit ( char c ) { 
		if ( '0' <= c && c <= '9' )
			return c - '0';//在ASCII表中,数字字符和它自己的真值正好相差一个字符‘0’
		else if ( 'a' <= c && c <= 'f' )
			return c - 'a' + 10;//这种方法参考了CSDN
		else if ( 'A' <= c && c <= 'F' )
			return c - 'A' + 10;//这种方法参考了CSDN
		else
			throw new HexFormatException("Invalid hexadecimal char: " + c);
	}
}

编程4-统计学生成绩

题目

编写程序,输入至少10个数作为学生成绩,以"-1"作为成绩输入的结束,需要对成绩进行有效性判断,如果输入的成绩数据不为整数(参照 Scanner类的定义,nextInt方法会抛出InputMismatchException),需捕获异常,提示“请输入整数成绩”;如果输入的成绩数目不足10个,抛出并捕获数目不足异常,并提示“请输入至少10名学生的成绩”(可自定义异常)。如果输入有效,显示当前输入成绩的从高到低排序结果。不管发生何种情况,都显示“你已输入x名学生的成绩”。 

在一切正常情况下的代码

import java.util.*;

public class Main {
	public static void main (String[] args){
		Scanner scanner = new Scanner(System.in);
		List<Integer> scores = new ArrayList<>(); //ArrayList方法参考菜鸟教程
		int score = 0;
		System.out.println("请输入学生成绩(输入-1结束):");	//1 2 3 4 5 6 7 8 9 10
		while(true) {
			score = scanner.nextInt();
			if (score == -1)
				break;
			scores.add(score);
		}
		System.out.println("你已输入" + scores.size() + "名学生的成绩");
		scores.sort(Comparator.reverseOrder());	//菜鸟教程:sort() 方法根据指定的顺序对动态数组中的元素进行排序。
		for (int i : scores) {
            System.out.print(i + " ");
        }
	}
}
请输入学生成绩(输入-1结束):
1 2 3 4 5 6 7 8 9 10 -1
你已输入10名学生的成绩
10 9 8 7 6 5 4 3 2 1

加了异常处理后的代码

异常情况

代码

import java.util.*;

class InsufficientScoresException extends Exception {
    public InsufficientScoresException(String message) {
        super(message);
    }
}

public class Main {
	public static void main (String[] args){
		Scanner scanner = new Scanner(System.in);
		List<Integer> scores = new ArrayList<>(); //ArrayList方法参考菜鸟教程
		int score = 0;
		System.out.println("请输入学生成绩(输入-1结束):");	//1 2 3 4 5 6 7 8 9 10
		try{
			while(true) {
				score = scanner.nextInt();
				if (score == -1)
					break;
				scores.add(score);
			}
			if (scores.size() < 10) {
				throw new InsufficientScoresException("成绩数目不足,至少需要10个成绩。");
			}
			scores.sort(Comparator.reverseOrder());	//菜鸟教程:sort() 方法根据指定的顺序对动态数组中的元素进行排序。
			System.out.println("成绩从高到低排序结果:");
			for (int i : scores) {
				System.out.print(i + " ");
			}
			System.out.println();
		} catch (InputMismatchException e) {
			System.out.println("请输入整数成绩");
		} catch (InsufficientScoresException e) {
			System.out.println(e.getMessage());
		} finally {
			System.out.println("你已输入" + scores.size() + "名学生的成绩。");
		}		
	}
}

测试 

测试1

请输入学生成绩(输入-1结束):
1 2 3 4 5 6 7 8 9 10 -1
成绩从高到低排序结果:
10 9 8 7 6 5 4 3 2 1 
你已输入10名学生的成绩。

测试2

请输入学生成绩(输入-1结束):
1 2 3 4 5 6 7 8 9 10.1 -1
请输入整数成绩
你已输入9名学生的成绩。

测试3

请输入学生成绩(输入-1结束):
1 2 3 4 5 6 7 8 9 -1
成绩数目不足,至少需要10个成绩。
你已输入9名学生的成绩。

  • 21
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值