运行时
应用一:描述长方形
要考虑程序的问题,传入的参数不符合要求
package Exception;
//运行时异常的应用
/*
描述长方形
行为:表达自己的长和宽/要考虑一旦参数传入不符合要求程序直接结束
*/
class NoEdge extends RuntimeException{//定义异常类
NoEdge(){
super();
}
NoEdge(String s){//将信息传入
super(s);
}
}
class Rectangle{
private int length;
private int width;
Rectangle(int length,int width){
if(length<=0||width<=0){
throw new NoEdge("边长输入错误!!");
}
this.length=length;
this.width=width;
}
public String ToString(){
return "长为:"+length+" 宽为:"+width+"";
}
}
public class ExceptionTest {
public static void main(String[] args){
Rectangle R = new Rectangle(4,0);
System.out.println(R.ToString());
}
}
————————————————————————————————————————————————————
编译时
加上异常类型转换
应用二:描述李老师讲课
考虑问题出现蓝屏
package Exception;
/*编译异常
描述李老师使用电脑上课
安全隐患为:电脑会蓝屏
*/
//异常类
class BlueException extends Exception {//蓝屏异常
BlueException(){
super();
}
BlueException(String s){
super(s);
}
}
//电脑
class Computer{
private int state=0;//电脑的状态
void Run()throws BlueException{
if(state==0){
throw new BlueException("电脑蓝屏了!!");
}
System.out.println("电脑运行!!!");
}
void ComputerReset(){
state=1;
System.out.println("电脑重启了!!");
}
}
//老师
class Teacher{
private String name;
private Computer notebook;
Teacher(String name){
this.name=name;
notebook =new Computer();
}
public void Prelect(){
try{//只负责检测
notebook.Run();//使用电脑上课
//传递一个异常对象给catch
}
catch(BlueException B){
//要写出蓝屏后具体的解决方法————重启
System.out.println(B.toString());//toString:返回异常信息/名字+内容
B.printStackTrace();//将此throwable和其追溯打印到指定的打印流
notebook.ComputerReset() ;//重启
}
System.out.println(name+"老师,上课!!!");
}
}
public class ExceptionTest {
public static void main(String[] args){
Teacher T = new Teacher("Li");
T.Prelect();
}
}
声明:是自己没有办法解决,通过不断向上声明到虚拟机,虚拟机给出最后的处理方式:显示异常和终止程序
捕获:自你自己可以给出解决的方法,然后程序可以继续的正常运行
编译时异常:要声明要捕获(给出处理方式)
异常处理的核心思想:解决安全隐患,提前想到问题并且给出具体的解决方式。有可能一直都不运行,但是是有 存在的价值的
1392

被折叠的 条评论
为什么被折叠?



