异常
广义:程序出现我问题
程序运行出现不正常的情况 例如数据输入问题,文件在被读取时被强制删除 出现异常jvm(虚拟机)停止运行后续程序无法正常运行
Java默认处理机制:将出现的异常按照不同类型分类,为没种异常封装进行表示,出现某种异常抛出此类对象,终止虚拟机的运行。
使用异常处理机制,对程序运行出现的异常进行捕捉并进行处理。
常见异常类型
/*int a=0; int b=0; System.out.println(a/b);ArithmeticException算数异常 */ //String s="abc"; //s.charAt(5);//StringIndexOutOfBoundsExceptionzifu 字符索引越界 int[] a = new int[5]; //System.out.println(a[6]);ArrayIndexOutOfBoundsException数组索引越界 String S=null; //S.length();NullPointerException空指针异常 Object w=new Integer(10); //String r=(String)w;ClassCastException类型转异常 //int p=Integer.parseInt("10a");NumberFormatException数字格式化异常
error:错误 程序无法处理 虚拟机内部错误,内部不够用
异常处理:在编码时针对可能出现问题的代码(经验问题)预先编写处理机制
运行
出现异常
执行处理机制
运行后续程序
int q=10;
int e=0;
try{
System.out.println(q/e);//算数运算
}catch (ArithmeticException io)//异常类型{
io.printStackTrace();//打印异常类型及异常语句
System.out.println("算数错误");
}finally{
System.out.println("林青霞");
}
System.out.println("林青霞");
}
Finally:
import java.io.FileInputStream;
import java.io.FileNotFoundException;
public class Dome2 {
public static void main(String[] args) {
int q=10;
int e=0;
try{
System.out.println(q/e);//算数运算 操作
}catch ( StringIndexOutOfBoundsException io)
{
io.printStackTrace();//打印异常类型及异常语句
System.out.println("算数错误");
}catch (Exception ex)//可以捕获任意异常,但要放到最后
{
ex.getMessage();
System.out.println("异常");
}
finally //捕获异常失败必定执行代码块的内容
{
System.out.println("张曼玉");
}
System.out.println("林青霞");
/*String s=null;
try{
s.length();
}catch (NullPointerException cb)//
{
cb.printStackTrace();
System.out.println("空指针");
}
System.out.println("算罗布");*/
FileInputStream in=null;
try{
in=new FileInputStream("D:demo3.txt");//文件查找失败
} catch (FileNotFoundException fileNotFoundException) {
fileNotFoundException.printStackTrace();
}finally {
System.out.println("系统繁忙,稍后再试");
}
}
}
throws:此方法可能会出现给定异常该方法不处理异常 交给方法调用处理 谁调用谁处理
检查期异常:在编码时主动提示 去处理异常
运行期异常:编码时不会主动提示 。
import java.util.Arrays;
public class Demo4 {
public static void main(String[] args) {
Arrays[]arr=new Arrays[1];
System.out.println(arr.length);
System.out.println(arr[2]);
}
public static void test(Arrays[] arr )throws ArrayIndexOutOfBoundsException{
//System.out.println(arr[6]);
throw new ArrayIndexOutOfBoundsException("数组越界");
}
}
区别在于异常类是否继承runtimexpection
throws(类型) :用在方法声明表示此方法出现某种类型异常,不处理
throw(对象):在方法体中 在方法体中抛出具体异常对象,该方法终止运行
自定义异常类
public class Scoreex extends Exception{
public Scoreex (String message){
super(message);
}
}
根据业务需求定义异常类型
分数错误:
import java.util.Scanner;
public class Score {
public static void main(String[] args) throws Scoreexp {
int score = 0;
Scanner s=new Scanner(System.in);
score=s.nextInt();
if(score>100||score<0){
throw new Scoreexp("分数错误");
}else{
System.out.println("你的分数为"+score);
}
}
}