什么是异常:在运行期间发生问题的就是异常。
异常和错误的区别:
异常是在运行时发生的,通常会有针对性的处理,而错误是jvm所在的系统反馈给jvm的,无法针对处理,往往只能修改代码。
异常的体现:
class ExceptionDemo
{
public static void main(String[] args)
{
int[] arr = new int[3];
System.out.println(arr[0]);
System.out.println(arr[3]);//该句运行时发生了ArrayIndexOutOfBoundsException,导致程序无法继续执行。程序结束。
System.out.println("over"); //由于上面代码发生了异常,此句代码不会执行
}
}
错误的体现
int[] arr = new int[1024*1024*100];//OutOfMemoryError 开辟了过大的数组空间,导致JVM在分配数组空间时超出了JVM内存空间,直接发生错误
异常的应用:
在编写程序时,必须要考虑程序的问题情况。比如在写功能时,需要接受参数,在使用功能中使用接受到的参数时,首先需要先对参数数据进行合法的判断,数据若不合法,应该告诉调用者,传递合法的数据进来。这时需要使用异常这种方法来告诉调用者。
public class 异常01 {
public static void main(String[] args) {
int[] arr=new int[4];
for(int i=0;i<arr.length;i++) {
arr[i]=i;
}
int n=getNumber(arr, 6);
System.out.println(n);
}
public static int getNumber(int[] arr,int index) {
if(arr==null) {
throw new NullPointerException("arr指向的数组不存在");
}
if(index<0||index>arr.length) {
throw new ArrayIndexOutOfBoundsException("错误的角标,"+index+"索在数组中不存在");
}
int n=arr[index];
return n;
}
}
自定义异常
public class 异常02 {
public static void main(String[] args) {
people p=new people("Tom",1000);
}
}
class NoAgeException extends RuntimeException{//自定义异常必须是继承Throwable,或者继承Throwable的子类。
public NoAgeException(){
super();
}
public NoAgeException(String message){
super(message);
}
}
class people{
private String name;
private int age;
public people(String name,int age) {
if(age<0||age>200) {
throw new NoAgeException(age+"年纪不符合现实");
}
}
}
异常分两种:
编译时异常:编译器会检测的异常。
运行时异常:编译器不会检测的异常。不需要声明。声明也可以,如果声明了,无外乎就是让调用者给出处理方式
声明:将问题标识出来,报告给调用者。如果函数内通过throw抛出了编译时异常,而没有捕获,那么必须通过throws进行声明,让调用者去处理。
捕获格式:
try
{
//需要被检测的语句。
}
catch(异常类 变量)//参数。
{
//异常的处理语句。
}
finally
{
//一定会被执行的语句。
}
public class 异常03 {
public static void main(String[] args) {
practice p=new practice();
try {
p.show(1);//当调用声明异常的方法时要么捕获,要么继续声明
} catch (Exception e) {
System.out.println("异常发生了");
}
finally{
System.out.println("一定会发生的代码");
}
}
}
class practice{
void show(int i) throws Exception{
if(i>0) {
throw new Exception();
}else {
System.out.println("i am sure");
}
}
}