第一题:
编写一个类ExceptionTest,在main方法中使用try-catch-finally语句结构实现:
在try语句块中,编写两个数相除操作,相除的两个操作数要求程序运行时用户输入;
在catch语句块中,捕获被0除所产生的异常,并输出异常信息;
在finally语句块中,输出一条语句
package shixun6;
import java.util.Scanner;
public class ExceptionTest extends Exception{
private static final int Scanner = 0;
private static Scanner sc;
public void ExceptionText(){
System.out.println("分母不能为0");
}
public static void main(String[] args) {
int a,b,c;
System.out.println("输入两个数:\n");
Scanner sc=new Scanner(System.in);
a=sc.nextInt();
b=sc.nextInt();
try{
c=a/b;
}
catch(ArithmeticException e){
System.out.println("分母不能为0");
}
}
private static int Scanner(int i, int j) {
// TODO Auto-generated method stub
return 0;
}
}
运行结果:
import java.util.InputMismatchException;
import java.util.Scanner;
public class yuan {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
double a;
System.out.println("输入1个半径:\n");
try{
a=sc.nextDouble();
}catch(InputMismatchException e){
System.out.println("输入类型不匹配");
运行结果:
package shixun6;
import java.util.*;
public class sfz {
static void pop(int l)throws IllegalArgumentException{
if(l<18||l>18) {
throw new IllegalArgumentException("不是18位数");
}
}
public static void main(String[] args) {
// TODO 自动生成的方法存根
Scanner rd=new Scanner(System.in);
String id;
int n;
id=rd.next();
n=id.length();
try {
pop(n);
System.out.println("身份证:"+id);
}catch(IllegalArgumentException e){
System.out.println(e);
}
}
}