异常关键字throws和throw

关键字 throws

在声明一个方法时,明确这个方法可能抛出xx异常,说明这些异常在方法中没有try…catch处理,而由上层调用者处理

语法格式:
[修饰符] 返回值类型 方法名([形参列表])[throws 异常]{
}

说明:throws后面可以接多个异常,一般有多个异常时,如果有包含关系,那么只写范围大的异常.

throws和方法重写:

方法重写的要求:
(1)方法名必须相同
(2)形参列表必须相同
(3)返回值类型
基本数据类型和void:必须相同
引用数据类型:小于等于原方法的数据类型
(4)权限修饰符
大于等于原方法的权限修饰符
(5)抛出的异常类型的列表
抛出的异常类型的范围小于等于原方法的范围

public class TestThrows {
	public static void main(String[] args) {
	
		try {
			divide(3,0);
		} catch (ArithmeticException e) {
			System.out.println("除数为0");
		}
	}
	public static int divide(int a,int b)throws ArithmeticException {
		return a/b;
	}

}

关键字 throw

异常对象:
(1)JVM抛出的
(2)程序员主动抛出的

throw用于主动抛出异常,无论是JVN抛出的异常还是程序员主动抛出的异常,最终都是用try…catch来处理

语法格式:
throw 异常对象

用throw抛出的异常必须直接用try…catch来处理,如果不处理,那么后面的代码都是不可达的代码

public class TestThrow {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO 自动生成的方法存根

	}
	public void tset1() {
		try {
			//匿名的异常对象
			throw new RuntimeException();
			
		} catch (Exception e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}
		
		System.out.println("其他代码");
		
	}
	public void tset2() {
		try {
			//有名字的异常对象
			RuntimeException e = new RuntimeException();
			throw e;
			
		} catch (Exception e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}
		
		System.out.println("其他代码");
		
	}

}

做一个练习
需求:(1)从键盘输入用户名.密码.检验码
(2) 当检验码错误的时候用异常来处理

public class TestThrow {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		try {
			login();
		} catch (Exception e) {
			// TODO 自动生成的 catch 块
			System.out.println(e.getMessage());
		}

	}
	
	/*需求:从键盘输入用户名.密码.检验码
	 * 当检验码错误的时候用异常来处理
	 * 
	 * */
	public static void login() throws Exception {
		Scanner sca = new Scanner(System.in);
		System.out.println("请输入用户名");
		String uers = sca.next();
		
		System.out.println("请输入密码");
		String password = sca.next();
		
		String code = "1234";
		System.out.println("请输入检验码");
		String check = sca.next();
		if(!code.equals(check)) {
			throw new Exception("校验码输入错误");
		}
	}
}

说明:在throw抛出异常时,如果没有try…catch来处理,相当于return,但是无法返回值,只能返回异常对象
Exception中的一个方法;
String getMessage() 这个方法用异常对象.getMessage()用来返回异常信息,异常的构造器可以创建一个带消息的对象.

发布了64 篇原创文章 · 获赞 15 · 访问量 2453

猜你喜欢

转载自blog.csdn.net/qq_40742223/article/details/104719828
今日推荐