zoukankan      html  css  js  c++  java
  • java中异常的抛出:throw throws

    java中异常的抛出:throw throws

    Java中的异常抛出

    语法:

    public class ExceptionTest{
        public void 方法名(参数列表) throws 异常列表{
            //调用会抛出异常的方法或者抛出新的异常(throw new Exception();)
        }
    }
    

    注:throws 异常列表位于方法体之前,可抛出多种类型的异常,每个类型之间用逗号隔开

    例如:

    public class ExceptionTest{
    	public void divide(int one,int two) throws Exception{
    		if(two==0){
    			throw new Exception("两数相除,除数不能为0!");
    		}
    		else{
    			System.out.println("两数相除,结果为:"+one/two);
    		}
    	}
    }
    

    如果某个方法调用到了会抛出异常的方法,有以下两种解决方案:

    1.添加try-catch去捕获异常进行处理

    例如:

    public class ExceptionTest {
    	public static void main(String[] args) {
    		try{
    			divide(5,0); // 调用了会抛出异常的方法divide();
    		}catch(Exception e){
    			System.out.println(e.getMessage());
    		}
    	}
    	public static void divide(int one,int two) throws Exception{
    		if(two==0){
    			throw new Exception("两数相除,除数不能为0!");
    		}
    		else{
    			System.out.println("两数相除,结果为:"+one/two);
    		}
    	}
    }
    

    运行结果:

    两数相除,除数不能为0!

    2.添加throws声明将异常抛出给更上一层的调用者(此方法无法处理异常,将异常再次抛出)

    nice ,马飞~

    例如:

    public class ExceptionTest {
    	public static void main(String[] args) throws Exception { //添加throws声明
    		divide(5,0);
    	}
    	public static void divide(int one,int two) throws Exception{
    		if(two==0){
    			throw new Exception("两数相除,除数不能为0!");
    		}
    		else{
    			System.out.println("两数相除,结果为:"+one/two);
    		}
    	}
    }
    
  • 相关阅读:
    废水回收
    XJOI网上同步训练DAY6 T2
    XJOI网上同步训练DAY6 T1
    Codeforces 351B Jeff and Furik
    对拍 For Linux
    Codeforces 432D Prefixes and Suffixes
    Codeforces 479E Riding in a Lift
    Codeforces 455B A Lot of Games
    Codeforces 148D Bag of mice
    Codeforces 219D Choosing Capital for Treeland
  • 原文地址:https://www.cnblogs.com/wenqiangit/p/10974453.html
Copyright © 2011-2022 走看看