黑马程序员java自学总结之--异常

来源:互联网 发布:校园网络贷款小品剧本 编辑:程序博客网 时间:2024/04/28 18:14
------- android培训、java培训、期待与您交流! ----------
一.异常

1.异常:就是程序在运行时出现不正常情况。
异常由来:问题也是现实生活中一个具体的事物,也可以通过java的类的形式进行描述。并封装成对象。
其实就是java对不正常情况进行描述后的对象体现。

对于问题的划分:两种:一种是严重的问题,一种非严重的问题。

对于严重的,java通过Error类进行描述。
对于Error一般不编写针对性的代码对其进行处理。

对与非严重的,java通过Exception类进行描述。
对于Exception可以使用针对性的处理方式进行处理。

无论Error或者Exception都具有一些共性内容。
比如:不正常情况的信息,引发原因等。

Throwable
Error
Exception
2,异常的处理
java 提供了特有的语句进行处理。
try
{
需要被检测的代码;
}
catch(异常类 变量)
{
处理异常的代码;(处理方式)
}
finally
{
一定会执行的语句;
}
3,对捕获到的异常对象进行常见方法操作。
String getMessage():获取异常信息。
class Demo{int div(int a,int b)throws Exception//在功能上通过throws的关键字声明了该功能有可能会出现问题。{return a/b;}}class ExceptionDemo{public static void main(String[] args){Demo d = new Demo();try{int x = d.div(4,1);System.out.println("x="+x);}catch (Exception e)//Exception e = new ArithmeticException();{System.out.println("除零啦");System.out.println(e.getMessage());// / by zero;System.out.println(e.toString());// 异常名称 : 异常信息。e.printStackTrace();//异常名称,异常信息,异常出现的位置。//其实jvm默认的异常处理机制,就是在调用printStackTrace方法。//打印异常的堆栈的跟踪信息。}System.out.println("over");}}


示例1:

在函数上声明异常。

便于提高安全性,让调用出进行处理。不处理编译失败。

class Demo{int div(int a,int b)throws Exception//在功能上通过throws的关键字声明了该功能有可能会出现问题。{return a/b;}}class ExceptionDemo1{public static void main(String[] args) //throws Exception{Demo d = new Demo();try{int x = d.div(4,0);System.out.println("x="+x);}catch (Exception e)
示例2:
毕老师用电脑上课。开始思考上课中出现的问题。比如问题是电脑蓝屏。电脑冒烟。要对问题进行描述,封装成对象。可是当冒烟发生后,出现讲课进度无法继续。出现了讲师的问题:课时计划无法完成。
class LanPingException extends Exception{LanPingException(String message){super(message);}}class MaoYanException extends Exception{MaoYanException(String message){super(message);}}class NoPlanException extends Exception{NoPlanException(String msg){super(msg);}}class Computer{private int state = 3;public void run()throws LanPingException,MaoYanException{if(state==2)throw new LanPingException("蓝屏了");if(state==3)throw new MaoYanException("冒烟了");System.out.println("电脑运行");}public void reset(){state = 1;System.out.println("电脑重启");}}class Teacher{private String name;private Computer cmpt;Teacher(String name){this.name = name;cmpt = new Computer();}public void prelect()throws NoPlanException{try{cmpt.run();}catch (LanPingException e){cmpt.reset();}catch (MaoYanException e){test();throw new NoPlanException("课时无法继续"+e.getMessage());}System.out.println("讲课");}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("换老师或者放假");}}}{System.out.println(e.toString());}System.out.println("over");}}







0 0
原创粉丝点击