Java 异常

异常

      Throwable

      /           \

    Exception      Error(错误)

    /      \

RuntimeException  编译异常

  运行异常          抛出异常throw/异常处理try{...}catch{...}

修改代码

 

1.JVM 检测到 方法中异常(下面代码不再执行)  创建异常对象 向上抛给调用者(main方法)

2.main方法接收到异常 也不能处理 ,继续向上抛给调用者(JVM虚拟机)

3.虚拟机接收到 异常  在控制台打印异常对象信息(红字)并终止程序

 

异常的构造函数:

throw new Exception();

throw new Exception("xxxx异常,提示语句");

 

try finally 组合: 组合后面不执行

try中   有异常 异常后面的不执行

try 无异常  不执行catch

finally 最终都要执行

 

public class Demo01 {

public static void main(String[] args) throws Exception,ArrayIndexOutOfBoundsException{

int[] arr={};//null

try{

int i=getLast(arr); //异常处理之前编译报错

System.out.println(i); //上一句有异常 此句不执行

}catch(ArrayIndexOutOfBoundsException ex){//捕获异常 对象

System.out.println(ex); // Ctrl+T父异常类包含子异常类

}catch(Exception ex){ //异常类顺序 先小后大

System.out.println(ex); //没有重写toString()方法

}finally{ //可不写

System.out.println("一定会执行的代码");

}

System.out.println("helloworld"); //遇到异常也执行

}

public static int getLast(int[] arr2) throws Exception,//抛异常后编译报错 ArrayIndexOutOfBoundsException{

if(arr2.length==0){

throw new ArrayIndexOutOfBoundsException("空数组");

}

if(arr2==null){throw new Exception("数组为null");} //制造异常

int i=arr2[arr2.length-1];

return i;

}

}

 

 

异常在方法重写中细节

class Fu{

public void eat()throws Exception{}// 父类抛异常

                 // 父类没抛异常 子类重写也不能抛

}                   //只能(try...catch) 或 转为运行异常

class Zi extends Fu{

public void eat()throws Exception{ // 子类可以不抛异常

sleep();           // 子类抛异常范围/个数<=父类

}

public void sleep()throws Exception{// 抛异常方法被 其他方法调用时

                // 如果该方法不允许抛异常 只能(try...catch)

}

}

 

 

异常中常用方法

try {

int[] arr={};

if(arr.length==0){ throw new Exception("数组为空"); }

int i=arr.length-1;

} catch (Exception e) {

String message = e.getMesage();

System.out.println(message ); //异常的 原因

String result = e.toString();

System.out.println(result); //异常的 类型、原因

e.printStackTrace(); //异常的 类型、原因、位置

}

 

自定义异常

SourceGenerate Constructors from Superclass 根据父类生成构造 2

public class FushuException extends RuntimeException{//或继承Exception

public FushuException(){} // 无参构造 初始化异常对象

public FushuException(String str){super(str);} //有参构造 调用父类有参

}

public class Demo02 {

public static void main(String[] args) {

int[] arr={1,2,-3,4,5};

int sum=0;

try {

for(int i:arr){

checkNum(i);//检查数据

sum+=i;

}

System.out.println(sum);

} catch (Exception e) {

e.printStackTrace();

}

}

public static void checkNum(int score) throws Exception {

if(i<0){ //不符合条件 抛出异常

throw new FushuException("数组有负数,"+i);

}

}

}

 

posted @ 2019-01-06 21:47  博客张C  阅读(137)  评论(0编辑  收藏  举报