异常
Java代码在运行时期发生的问题就是异常。
在Java中,把异常信息封装成了一个类。当出现了问题时,就会创建异常类对象并抛出异常相关的信息(如异常出现的位置、原因等)。
Exception有继承关系,它的父类是Throwable。Throwable是Java 语言中所有错误或异常的超类,即祖宗类。
Throwable: 它是所有错误与异常的超类(祖宗类)
Error 错误
Exception 编译期异常,进行编译JAVA程序时出现的问题
RuntimeException 运行期异常, JAVA程序运行过程中出现的问题
public class Demo03 {
public static void main(String[] args){
int[] arr={};
try{
//可能会发生异常的语句
int a=get(arr);
System.out.println(a);
}catch(NullPointerException ex){
//如果发生该异常怎么处理
System.out.println(ex);
}catch(ArrayIndexOutOfBoundsException ex){
//如果发生该异常怎么处理
System.out.println(ex);
}finally{
//不管发不发生异常都会执行的语句
System.out.println("finally执行了");
}
}
public static int get(int[] arr)throws NullPointerException,ArrayIndexOutOfBoundsException{
if(arr==null){
throw new NullPointerException("数组为空!");
}
if(arr.length==0){
throw new ArrayIndexOutOfBoundsException("数组长度为0");
}
int i=arr[arr.length-1];
return i;
}
}
public class Demo04 {
public static void main(String[] args){
int[] arr={};
int a;
try {
a = get(arr);
System.out.println(a);
} catch (ArrayIndexOutOfBoundsException e) {
e.printStackTrace();
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
public static int get(int[] arr)throws NullPointerException,ArrayIndexOutOfBoundsException,Exception{
if(arr==null){
throw new NullPointerException("数组为空!");
}
if(arr.length==0){
throw new ArrayIndexOutOfBoundsException("数组长度为0");
}
int i=arr[arr.length-1];
return i;
}
}
public static void main(String[] args){
int[] arr={};
try{
//可能会发生异常的语句
int a=get(arr);
System.out.println(a);
}catch(Exception ex){
//getMessage()只打印异常信息
//System.out.println(ex.getMessage());
//toString()打印异常对象和异常信息
//System.out.println(ex.toString());
//printStackTrace()以红字的方式打印异常对象、信息、位置
ex.printStackTrace();
}finally{
//不管发不发生异常都会执行的语句
System.out.println("finally执行了");
}
}
异常:指程序在编译、运行期间发生了某种异常(XxxException),我们可以对异常进行具体的处理。若不处理异常,程序将会结束运行。
错误:指程序在运行期间发生了某种错误(XxxError),Error错误通常没有具体的处理方式,程序将会结束运行。Error错误的发生往往都是系统级别的问题,都是jvm所在系统发生的,并反馈给jvm的。我们无法针对处理,只能修正代码。


浙公网安备 33010602011771号