Java异常
任何一种程序设计语言设计的程序在运行时都有可能出现错误,例如除数为0,数组下标越界,要读写的文件不存在等等。
捕获错误最理想的是在编译期间,但有的错误只有在运行时才会发生。
对于这些错误,一般有两种解决方法:
➢遇到错误就终止程序的运行。
➢由程序员在编写程序时,就考虑到错误的检测、错误消息的提示,以及错误的处理。
异常的特点
1、程序执行中发生的不正常情况
2、开发过程中的语法错误不叫异常
Java程序运行过程中所发生的异常事件可分为两类:
➢Error:JVM系统内部错误、资源耗尽等严重情况//无法控制,不处理 . ➢Exception:其它因编程错误或偶然的外在因素导致的一般性问题。比如:空指针访问、试图读取不存在的文件等。

如图,错误后跟着两个类
第一个是虚拟机的错误如内存溢出,栈溢出
第二个是Windows错误列如浏览器崩溃
Exception:
1、IOE…是需要你处理的异常(编译时就报错的)
2、Runtime…是运行期间的错误(编译时看不出来)

Exception异常分为两大类
一、运行时异常:都是RuntimeException类及其子类异常
二、非运行时异常(编译异常):是RuntimeException以外的异常

异常处理

public class demo{
public static void main(String[] args){
/*(int[] num = new int[5];
*System.out,println(num[5]);
*int a = 1;
*System.out.println(a);
*这里不会输出a 因为会报错 num[]数组下标越界
*怎么让它不影响下面的操作用try- catch - finaly
*/
int[] num = new int[5];
try{
System.out.println(num[5]);//可能会发生异常,就用try括起来
}catch(ArrayIndexOutOfBoundsException e){//下标越界异常
e.printStackTrace(); //打印异常e里面的栈信息
System.out.println("捕获到异常");//提示异常信息
}
int a = 1;
System.out.println(a);
//这里尽管也会显示异常但是会输出a的值;
//try{}花括号里面的定义的不能被外边获取是一个封闭的
//catch()捕获的异常只能是该异常类或者它的父类
}//多个异常
public class demo1{
public static void main(String[] args){
File file = null;
try{
file = new File("xxxx");//创建文件异常
file.creatNewFile();
Class.forNmae("");
Thread.sleep(124); //毫秒
}catch(IOException e){
e.printStackTrace();
}catch(ClassNotFoundException e){
e.printStackTrace();
}catch(TnterruptedException e){
e.printStackTrace();
}
}
//可以用一个catch
try{
file = new File("xxxx");
file.creatNewFile();
Class.forNmae("");
Thread.sleep(124);
}catch(Exception e){
e.printStackTrace();
}
}
//除了RuntimeException及子类之外的异常都是编译异常,需要通过try()或抛出的方式处理
public void test() throws FileNotFoundException{
FileInputStream fs = new FileInputStream("XXX");//此处有异常
//要么处理,要么不处理把异常抛出去,谁调用test()谁处理
//处理资源释放,final(关闭);
}
如图。除非你手动关闭程序或者出现error 断点等很极端的情况。都会执行finally

如图,没有异常时,catch语句不执行,但是final语句肯定执行,倘若try语句中有return语句,会在执行完final语句后去执行try中的return语句后再继续往下走
如另一图,在语句二报异常,会去找他的catch语句,然后final语句,再往下,至于try语句中的语句三、语句四等等会忽略。
抛出异常throws
try catch(抓 自己处理)
throws(抓 交给别人处理)

throw
总是出现在方法体里面
语法格式:throw new excename
public static void test()throws ArithmeticException{
try{
int x = 12 / 0;
}catch(Exception e){
//自己处理
e.printStackTrace();
//怎么让别人处理这个异常呢,用throw把它抛出去
throw new ArithmeticException();
}
}
















