黑马程序员——面向对象-异常

来源:互联网 发布:文学书籍推荐 知乎 编辑:程序博客网 时间:2024/05/18 11:46

------Java培训、Android培训、iOS培训、.Net培训、期待与您交流! -------

 

 

异常处理的捕捉模式:

class FuShuIndexException extends Exception {FuShuIndexException() {}FuShuIndexException(String msg) {super(msg);}}class Demo {public int method(int[] arr, int index) throws Exception// throws// NullPointerException,FuShuIndexException{if (arr == null)throw new NullPointerException("没有任何数组实体");if (index < 0)throw new FuShuIndexException();return arr[index];}}class ExceptionDemo4 {public static void main(String[] args) throws Exception {int[] arr = new int[3];Demo d = new Demo();try {int num = d.method(null, -1);System.out.println("num=" + num);}catch (NullPointerException e) {System.out.println(e.toString());} catch (FuShuIndexException e) {System.out.println("message:" + e.getMessage());System.out.println("string:" + e.toString());e.printStackTrace();// jvm默认的异常处理机制就是调用异常对象的这个方法。System.out.println("负数角标异常!!!!");}/* * catch(Exception e)//多catch父类的catch放在最下面。 { *  * } */System.out.println("over");}}


异常转化:

/* 毕老师用电脑上课。 问题领域中涉及两个对象。 毕老师,电脑。 分析其中的问题。 比如电脑蓝屏啦。冒烟啦。 */class LanPingException extends Exception {LanPingException(String msg) {super(msg);}}class MaoYanException extends Exception {MaoYanException(String msg) {super(msg);}}class NoPlanException extends Exception {NoPlanException(String msg) {super(msg);}}class Computer {private int state = 2;public void run() throws LanPingException, MaoYanException {if (state == 1)throw new LanPingException("电脑蓝屏啦!!");if (state == 2)throw new MaoYanException("电脑冒烟啦!!");System.out.println("电脑运行");}public void reset() {state = 0;System.out.println("电脑重启");}}class Teacher {private String name;private Computer comp;Teacher(String name) {this.name = name;comp = new Computer();}public void prelect() throws NoPlanException {try {comp.run();System.out.println(name + "讲课");} catch (LanPingException e) {System.out.println(e.toString());comp.reset();prelect();} catch (MaoYanException e) {System.out.println(e.toString());test();// 可以对电脑进行维修。// throw e;throw new NoPlanException("课时进度无法完成,原因:" + e.getMessage());}}public void test() {System.out.println("大家练习");}}class ExceptionTest {public static void main(String[] args) {Teacher t = new Teacher("毕老师");try {t.prelect();} catch (NoPlanException e) {System.out.println(e.toString() + "......");System.out.println("换人");}}}


异常这部分是很重要的,与之重要性相同的是学习难度也挺大。主要在于理解抛出和捕捉两种模式。

我是这样理解的:抛出就是在程序本身解决不了的要抛出给用户看到。而捕捉的异常一般是可以在程序内部进行调整的,当然也可以抛出。有理解不到位的地方,大家多指点。

 

 

 

 

 

0 0
原创粉丝点击