java实训题异常捕获

ĉ编译一个可演示用户自定义常用法的程序,该程序接受用户输入的学生人数,当输入一个负数时,认为是非法的,用户自定义异常捕获此错误

import java.io.*;

class XT008204 {

public static void main(String args[]){

String s="";

int t;

while ( true ) {

try {

System.out.print("请输入学生人数:");

BufferedReader in=new

BufferedReader(new InputStreamReader(System.in));

s=in.readLine();

t=Integer.parseInt(s);

if ( t<0 )

throw new NegException("人数不能为负数!");

System.out.println("你输入的人数是:"+t);

break;

}//end try

catch(IOException e) { System.out.println(e); }

catch(NegException e) { System.out.println(e); }

}//end while

}//end main()

}//end class

class NegException extends Exception{

public NegException(String message){

super(message);

}

}

 

//测试类
import java.util.Scanner;
public class StudentTest {
    public static void main(String[] args) throws MyException {
        Scanner in=new Scanner(System.in);
        System.out.println("请输入学生人数:");
        int count=in.nextInt();
        if(count<0){
            throw new MyException("人数不能为负数");
        }
        System.out.println("输入的学生人数为:"+count);
    }
}


//自定义异常类
public class MyException extends Exception {
    public MyException(String error){
        super(error);
    }
}

如有帮助,望采纳。点击我回答右上角的【采纳】按钮。

写一个类,继承Exception类就可以实现。

您好,我是有问必答小助手,您的问题已经有小伙伴解答了,您看下是否解决,可以追评进行沟通哦~

如果有您比较满意的答案 / 帮您提供解决思路的答案,可以点击【采纳】按钮,给回答的小伙伴一些鼓励哦~~

ps:问答VIP仅需29元,即可享受5次/月 有问必答服务,了解详情>>>https://vip.csdn.net/askvip?utm_source=1146287632