学习要点
- throw的作用
- throws的作用
class User{ private int age; public void setAge(int age){ if(age<0){ RuntimeException e = new RuntimeException("年龄不能为负数");//生成异常对象 throw e;//抛出异常对象 } this.age = age; } }
class Test{ public static void main(String args[]){ User user = new User(); user.setAge(-20); } }
=====================================================
class User{ private int age; public void setAge(int age) throws Exception{ //声明 setAge函数有可能出现Exception异常 if(age<0){ Exception e = new Exception("年龄不能为负数");//生成异常对象 throw e;//抛出异常对象 } this.age = age; } }
class Test{ public static void main(String args[]) { User user = new User(); try{ user.setAge(-20); } catch(Exception e){ System.out.println(e); } } }
时间: 2024-11-05 19:53:18