• java基础异常处理


    异常的定义:中断了正常指令流的事件。

    try..catch..finally结构:

    class Test{
        public static void main(String[] args){
            System.out.println(1);
            try{
                System.out.println(2);
                int i = 1 / 0;
                System.out.println(3);
            }
            catch(Exception e){
                e.printStackTrace();
                System.out.println(4);
            }
            finally{
                System.out.println(5);
            }
            System.out.println(6);
        }
    }

    输出结果:

        D:Javacode练习十二>java Test
    1
    2
    java.lang.ArithmeticException: / by zero
            at Test.main(Test.java:6)
    4
    5
    6
    

      

     throw与throws关键字

    class User{
    	private int age;
    	public void setAge(int age) throws Exception{
    		if(age <= 0){
    			Exception e = new Exception("input age is error!");
    			throw e;
    		}
    		else{
    			this.age=age;
    		}
    		
    	}
    }
    

      

    class Test{
        public static void main(String[] args){
            User u = new User();
            try{
                u.setAge(-20);
            }
            catch(Exception e){
                System.out.println(e);
            }
            
        }
    }
    D:Javacode练习十二>java Test
    java.lang.Exception: input age is error!
    

      

  • 相关阅读:
    年入50万的众生相
    【史上最全面经】银行类
    Dubbo背景和简介
    剑指Offer66题的总结、目录
    如何写一份更好的简历
    Linux命令 file
    Linux命令 umask
    Linux perm
    Linux 命令 which whereis locate find
    Linux命令 diff cmp patch
  • 原文地址:https://www.cnblogs.com/endust/p/11838762.html
Copyright © 2020-2023  润新知