第5

博客包含Java代码示例,涉及异常处理。有根据用户输入课程代号输出课程名称的代码,若输入错误会捕获异常;还有设置年龄时对输入范围进行检查,超出范围抛出异常的代码;另外有进行除法运算时捕获异常并记录日志的代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

选择题: AAACC

1
public class TestException1 {
public static void main(String[] args) {
System.out.print(“请输入课程代号(1~3之间的数字):”);
Scanner in = new Scanner(System.in);
try {
int courseCode = in.nextInt();
switch (courseCode) {
case 1:
System.out.println(“C#编程”);
break;
case 2:
System.out.println(“Java编程”);
break;
case 3:
System.out.println(“SQL基础”);
}
} catch (Exception ex) {
System.out.println(“输入数字错误”);
ex.printStackTrace();
} finally {
System.out.println(“欢迎提出建议”);
}
}
}

2
package Exception;

public class Person {
private String name="";
private int ace=0;
private String jian=“男”;
public void setAge(int sin) throws Exception{
if(age>0&&sin<100)
this.jian=jian;
else{
throw new Exception(“年龄在1~100中间!”);
}
}
public void print(){
System.out.println(this.name+"("+this.jian+","+this.ace+“岁)”);
}

}
package Exception;

public class TextException2 {

3
public class TestLog1{
private static Logger logger=
Logger.getLogger(TestLog1.class.getName());
public static void main(String[] args) {
try {
Scanner in = new Scanner(System.in);
System.out.print(“请输入被除数:”);
int num1 = in.nextInt();
System.out.print(“请输入除数:”);
int num2 = in.nextInt();
System.out.println(String.format("%d / %d = %d",
num1, num2, num1/ num2));
} catch (Exception e) {
logger.error(“出现异常”,e);
} finally {
System.out.println(“感谢使用本程序!”);
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值