第六次实训作业异常处理

1编写一个类ExceptionTest,在main方法中使用try-catch-finally语句结构实现:
•在try语句块中,编写两个数相除操作,相除的两个操作数要求程序运行时用户输入;
•在catch语句块中,捕获被0除所产生的异常,并输出异常信息;
•在finally语句块中,输出一条语句。

import java.util.*;
public class Zzw {

public static void main(String args[]) {
int s,a,b;
try {
a=new Scanner(System.in).nextInt();
b=new Scanner(System.in).nextInt();
s=a/b;
System.out.println(s);
}catch(ArithmeticException e) {
System.out.println("除数不能为0!");
}finally {
System.out.println("哈哈!");
}
}
}

![](https://img2018.cnblogs.com/blog/1632974/201906/1632974-20190606170419001-1445777833.png)

3.类的属性“身份证号码.id”设置值,当给的的值长度为18时,赋值给id,当值长度不是18时,抛出IllegalArgumentException异常,然后捕获和处理异常,编写程序实现以上功能。

import java.util.*;
public class yuan {
  static void pop(int a) throws IllegalArgumentException{
      if(a!=18) {
          throw new IllegalArgumentException("长度不是18");
      }
  }
  public static void main(String args[]) {
      Scanner b=new Scanner(System.in);
      String c;
      int d;
      c=b.next();
      d=c.length();
      try {
          pop(d);
          System.out.println("身份证号码");
          System.out.println(c);
      }catch(IllegalArgumentException e){
          System.out.println(e);
      }
      
  }
}

原文地址:https://www.cnblogs.com/tiantianna/p/10985986.html