zoukankan      html  css  js  c++  java
  • Java基础-throw和throws

    虽然了解一些有关 Java 的异常处理,但是发现自己对 throw 和 throws 二者还不是很清楚,所以想深入的理解理解。

    抛出异常的三种方式

    系统自动抛出异常、throw 和 throws三种方式。

    1、系统自动抛出异常

    public class ThrowTest {
    	
    	public static void main(String[] args) {
    		int a = 0;
    		int b = 1;
    		System.out.println(b / a);
    	}
    
    }
    

    运行该程序后系统会自动抛出 ArithmeticException 算术异常。

    Exception in thread "main" java.lang.ArithmeticException: / by zero
    	at com.sywf.study.ThrowTest.main(ThrowTest.java:8)
    

    2、throw
    throw 指的是语句抛出异常,后面跟的是对象,如:throw new Exception,一般用于主动抛出某种特定的异常,如:

    public class ThrowTest {
    	
    	public static void main(String[] args) {
    		String string = "abc";
    		if ("abc".equals(string)) {
    			throw new NumberFormatException();
    		} else {
    			System.out.println(string);
    		}
    	}
    
    }
    

    运行后抛出指定的 NumberFormatException 异常。

    Exception in thread "main" java.lang.NumberFormatException
    	at com.sywf.study.ThrowTest.main(ThrowTest.java:8)
    

    3、throws
    throws 用于方法名后,声明方法可能抛出的异常,然后交给调用其方法的程序处理,如:

    public class ThrowTest {
    
    	public static void test() throws ArithmeticException {
    		int a = 0;
    		int b = 1;
    		System.out.println(b / a);
    	}
    
    	public static void main(String[] args) {
    		try {
    			test();
    		} catch (ArithmeticException e) {
    			// TODO: handle exception
    			System.out.println("test() -- 算术异常!");
    		}
    	}
    
    }
    

    程序执行结果:

    test() -- 算术异常!
    

    throw 与 throws 比较

    1、throw 出现在方法体内部,而 throws 出现方法名后。
    2、throw 表示抛出了异常,执行 throw 则一定抛出了某种特定异常,而 throws 表示方法执行可能会抛出异常,但方法执行并不一定发生异常。

  • 相关阅读:
    Pro/Toolkit示例之一:异步启动ProE
    Formatted MessageBox/AfxMessageBox
    Pro/Toolkit示例之二:同步Dll程式
    模拟按钮控件BN_CLICKED消息事件
    详解ProToolkit注册文件
    C++函数指针
    Message Basic
    C++指针之间的赋值与转换规则总结
    CString&CStringA&CStringW之间的相互转换
    Devexpress组件之XtraBars.PopupMenu的使用
  • 原文地址:https://www.cnblogs.com/shanyingwufeng/p/10183853.html
Copyright © 2011-2022 走看看