java学习记录分享(九)

异常的常见语法

	java下有一个类叫做Throwable,其子类有Exception和Error,Exception可以捕获并补救,但Error无法补救。
	Exception下有很多子类,比如NullPointerException,SQLException,IOException等等。
public class Test{
		//1最简单的形式try-catch
		try{
			String str="hello";
			System.out.println(str);
		}catch(Exception ex){
			ex.printStackTrace();
		}
		//2try-catch-.....-catch
		//这里需要注意捕获异常的顺序,先具体后宽泛,否则编译器报错
		/*try{
			String str="hello";
			System.out.println(str);
		}catch(NullPointerException ex){
			ex.printStackTrace();
		}catch(Exception ex){
			ex.printStackTrace();
		}
		*/
		//3try-catch-finally
		//finally表示无论如何(是否发生异常,直接return)都会执行finally后的语句
		/*try{
			System.out.println("A");
			int num = 5/0;
		}catch(ArithmeticException ex){
			System.out.println("B");
		}finally
		System.out.println("C");
		//会换行打印A,B,C
		*/
		//4try-finally,并不会捕获异常,一般较少使用
}

throws

	一般表示该方法有使用风险,在使用该方法的时候要进行一定的操作
	方法一:在使用该方法时用try-catch包围
		class A {
			public void hi() throws IOException{
				System.out.println("你好");
			}
		}
		public class Test{
			public static void main(String[] args){
			try{
				A a=new A();
				a.hi();		//如果不使用try-catch包围则报错
			}catch(IOException ex){
				ex.printStackTrace();
			}
		}
	}
	方法二:将异常抛到上一层
		class A {
			public void hi() throws IOException{
				System.out.println("你好");
			}
		}
		public class Test{
			public static void main(String[] args) throws IOException{
				A a=new A();
				a.hi();	
		}
	}

throw

	表示该方法会造成不可挽回的后果,throw在方法主体中写,举个例子
			class A {
			public void hi() {
				System.out.println("你好");
				try{
				throw new IOException//直接抛出异常,但因为当场解决,所以在调用时不需要try-catch
			}catch(IOException ex){
			
			}
			}
		}
		public class Test{
			public static void main(String[] args) throws IOException{
				A a=new A();
				a.hi();	
		}
	}
	也可以这么解决
		class A {
			public void hi() throws Exception{
				System.out.println("你好");
				throw new IOException}
		}
		public class Test{
			public static void main(String[] args) throws Exception{
				A a=new A();
				a.hi();	
		}
	}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值