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 表示方法执行可能会抛出异常,但方法执行并不一定发生异常。

  • 相关阅读:
    FreeRTOS相关转载-(朱工的专栏)
    任务相关的API函数-uxTaskGetSystemState
    STM32用FreeRTOS时任务优先级和中断优先级说明
    STM32标准外设库中USE_STDPERIPH_DRIVER, STM32F10X_MD的含义
    C语言变量和函数命名规范
    Java学习笔记-命令模式
    leetcode-Search in Rotated Sorted Array -java
    Java学习笔记-单件模式
    Java学习笔记-问问题?-->静态方法
    TCP滑动控制
  • 原文地址:https://www.cnblogs.com/shanyingwufeng/p/10183853.html
Copyright © 2011-2022 走看看