java异常处理

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

import java.util.*;


public class ExceptionTest {
	public static void main(String[]args){
		int a,b;
		float c;
		try{
			Scanner in = new Scanner(System.in);
			System.out.println("请输入被除数a的值:");
			a = in.nextInt();
			System.out.println("请输入除数b的值:");
			b = in.nextInt();
			c = a/b;
			System.out.println("a/b="+c);
		}catch(ArithmeticException e){
			e.printStackTrace();
			System.out.println("程序异常");
		}
		finally{
			System.out.println("程序结束");
		}
	}

}

2 编写一个应用程序,要求从键盘输入一个double型的圆的半径,计算并输出其面积。测试当输入的数据不是double型数据(如字符串“abc”)会产生什么结果,怎样处理。

import java.util.*;

public class yuan{
	public static void main(String[]args){
		double r,s;
		double pi=3.14;
		try{
			Scanner in = new Scanner(System.in);
		    System.out.println("请输入半径r的大小:");
		    r = in.nextDouble();
		    s = pi*r*r;
		    System.out.println("圆的面积s="+s);
		}catch(InputMismatchException e){
			e.printStackTrace();
			System.out.println("程序异常");
		}
		finally{
			System.out.println("程序结束");
		}				
	}
}

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

import java.util.*;
public class MyException extends Exception {
	public MyException(String ErrorMessage){
		super(ErrorMessage);
	}
	public static void main(String[]args){
		String id;
		int a ;
		Scanner in = new Scanner(System.in);
		System.out.println("请输入id:");
		id = in.nextLine();
		a = id.length();
	}
	public class Tran{
		void avg(int a)throws MyException{
			if(a>18){
				throw new IllegalArgumentException("长度超过18位");
			}			
		}
	}
}

最后一个不知道为毛抛不出来,
有大佬来指点一下马

原文地址:https://www.cnblogs.com/BKKITO/p/10831035.html