首页 > 学院 > 开发设计 > 正文

Exception异常处理

2019-11-06 06:51:42
字体:
来源:转载
供稿:网友

要养成一个好习惯,在最后一个catch上去捕获最大的Exception,以防止程序出现一个未捕获的异常导 致程序退出。还要注意的是,若捕获的异常中有父子类关系的,一定是子类异常在上,父类异常在下。 例1:

package day03;/** * java异常捕获机制中的try-catch * @author Administrator * */public class ExceptionDemo1 { public static void main(String[] args) { System.out.PRintln("程序开始了"); try{ String str = "a"; System.out.println(str.length()); System.out.println(str.charAt(0)); System.out.println(Integer.parseInt(str));//a不能转换为int }catch(NullPointerException e){ System.out.println("出现了一个空指针!"); }catch(StringIndexOutOfBoundsException e){ System.out.println("下标越界了!"); /* * 要养成一个好习惯,在最后一个catch上去捕获最大的Exception,以防止程序出现一个未捕获的异常导 致程序退出。还要注意的是,若捕获的异常中有父子 * 类关系的,一定是子类异常在上,父类异常在下。 */ }catch(Exception e){ System.out.println("反正就是出了个错!"); } System.out.println("程序结束了"); }}

运行结果:

程序开始了1a反正就是出了个错!程序结束了

例2:finally示例:

package day03;/** * finally面试题 * @author Administrator * */public class ExceptionDemo3 { public static void main(String[] args) { System.out.println(test("0") + "," +test(null) + "," +test("")); } @SuppressWarnings("finally") public static int test(String str){ try { return '0'-str.charAt(0); } catch (NullPointerException e) { return 1; } catch (Exception e){ return 2; } finally{ return 3; } }}

运行结果:

3,3,3

例3:自定义exception示例。 自定义人类年龄不合法: 地异步写一个类继承至Exception,并重写父类的方法:

package day03;public class IllegalAgeException extends Exception { /** * 该异常表示年龄不合法 */ private static final long serialVersionUID = 1L; public IllegalAgeException() { super(); // TODO Auto-generated constructor stub } public IllegalAgeException(String message, Throwable cause) { super(message, cause); // TODO Auto-generated constructor stub } public IllegalAgeException(String arg0) { super(arg0); // TODO Auto-generated constructor stub } public IllegalAgeException(Throwable cause) { super(cause); // TODO Auto-generated constructor stub }}

第二步:新建一个Person人用户,设置年龄:

package day03;/** * 描述一个用户信息 */public class Person { private int age; public int getAge() { return age; } /** * 通常,方法中使用throw抛出什么异常,方法 声明的时候就要使用throws定义该异常的抛出。 * 方法上若使用throws声明了某些异常的抛出时,那么外界在调用该方法的时候就有一个强制要求,必须处理这些异常。 * 处理的手段有两种: 1.try-catch捕获该异常。2.接着向外抛出。 * 需要注意,当我们使用throw抛出的不是RuntimeException及其子类异常时,就必须处理这个异常。 * @param age * @throws IllegalAgeException */ public void setAge(int age) throws IllegalAgeException{ if(age<0||age>100){throw new IllegalAgeException("不符合人类年龄");} this.age = age; }}

第3步:使用自定义的异常测试:

package day03;public class TestPerson { public static void main(String[] args){ Person p = new Person(); try { p.setAge(1000); } catch (IllegalAgeException e) { e.printStackTrace(); }//这里会抛出异常。 System.out.println("他的年龄是:"+p.getAge()); }}

运行结果:

day03.IllegalAgeException: 不符合人类年龄 at day03.Person.setAge(Person.java:30) at day03.TestPerson.main(TestPerson.java:7)他的年龄是:0
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表