黑马Java学习笔记之-----异常
---------------------- android培训、java培训、期待与您交流! ----------------------
异常:
Java异常是Java提供的用于处理程序中错误的一种机制。(程序运行期出现的错误。)
tip:观察错误的名字和行号最重要。
异常体系:
Throwable:
|--Error:重大的问题,我们处理不了。也不需要编写代码处理。比如说内存溢出。
|--Exception:一般性的错误,是需要我们编写代码进行处理的。
|--RuntimeException:运行时异常,这个我们也不需要处理。其实就是为了让他在运行时出问题,然后我们回来修改代码。
异常的用法:
处理异常——————java 提供了特有的语句进行处理。 在程序中可以在方法后面使用throws关键字声明向外抛出异常 对于编译时异常,通常我们需要使用try……catch语句进行捕获 finally可以结合try……catch使用,出现异常,finally里面的代码也会执行
try
{
需要被检测的代码;
}
catch(异常类 变量)
{
处理异常的代码;(处理方式)
}
finally
{
一定会执行的语句;
}
对多异常的处理。
1,声明异常时,建议声明更为具体的异常。这样处理的可以更具体。
2,对方声明几个异常,就对应有几个catch块。不要定义多余的catch块。
如果多个catch块中的异常出现继承关系,父类异常catch块放在最下面。
建立在进行catch处理时,catch中一定要定义具体处理方式。
不要简单定义一句 e.printStackTrace(),
也不要简单的就书写一条输出语句。
throws和throw的区别:
throws使用在函数上。
throw使用在函数内。
throws后面跟的异常类。可以跟多个。用逗号隔开。
throw后跟的是异常对象。
finally代码块:定义一定执行的代码。finally中存放的是一定会被执行的代码。
通常用于关闭资源。finally只有一种情况不会执行。当执行到System.exit(0); fianlly 不会执行。
例题:
需求:
毕老师用电脑上课。
开始思考上课中出现的问题。
比如问题是
电脑蓝屏
电脑冒烟
要对问题进行描述,封装成对象。
可是当冒烟发生后,出现讲课进度无法继续。
出现了讲师的问题:课时计划无法完成。
class MaoYanException extends Exception
{
MaoYanException(String message)
{
super(message);
}
}
class LanPingException extends Exception
{
LanPingException(String message)
{
super(message);
}
}
class NoPlanException extends Exception
{
NoPlanException(String message)
{
super(message);
}
}
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("放假!");
}
}
}
---------------------- android培训、java培训、期待与您交流! ----------------------