第5次java作业

本文详细介绍了Java中异常处理的基本用法,包括如何使用try-catch-finally语句来捕获和处理运行时异常,如算术异常和输入不匹配异常。同时,深入探讨了自定义异常类,如IllegalArgumentException,并通过Person类的实例展示了如何在方法中抛出并捕获这些异常。

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

package work; import java.util.Scanner; public class ExceptionTest { public static void main(String[] args) { Scanner in = new Scanner(System.in); double n1 = in.nextDouble(); double n2 = in.nextDouble(); 11 double result; 12 try{ 13 result = n1/n2; 14 System.out.println(result); 15 }catch(ArithmeticException e){ 16 e.printStackTrace(); 17 }finally{ 18 System.out.println("finally"); 19 } 20 in.close(); 21 } 22 23 } 1 package work; 2 3 import java.util.InputMismatchException; 4 import java.util.Scanner; 5 6 public class Work2 { 7 public static void main(String[] args) { 8 Scanner in = new Scanner(System.in); 9 double radius; 10 try{ 11 radius = in.nextDouble(); 12 System.out.println(radius); 13 }catch(InputMismatchException e) 14 { 15 System.out.println("你输入的数据有点问题"); 16 } 17 } 18 } 1 package work; 2 3 public class Person { 4 private String name; 5 private int age; 6 private String id; 7 public String getName() { 8 return name; 9 } 10 public void setName(String name) { 11 this.name = name; 12 } 13 public int getAge() { 14 return age; 15 } 16 public void setAge(int age) { 17 this.age = age; 18 } 19 public String getId() { 20 return id; 21 } 22 public void setId(String id) throws IllegalArgumentException{ 23 if(id.length()!=18) 24 { 25 throw(new IllegalArgumentException()); 26 } 27 this.id = id; 28 } 29 } 1 package work; 2 3 public class IllegalArgumentException extends Exception{ 4 5 } 1 package work; 2 3 public class ExceptionTest2 { 4 5 public static void main(String[] args) { 6 Person p1 = new Person(); 7 Person p2 = new Person(); 8 try { 9 p1.setId("430122200009190315"); 10 p2.setId("110110110"); 11 } catch (IllegalArgumentException e) { 12 System.out.println("长度有误"); 13 } 14 15 16 } 17 18 }

转载于:https://www.cnblogs.com/mylyqc/p/11001245.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值