Java中的异常和错误
ASP站长网Java 中的异常机制,更好地提升程序的健壮性
 
throwable 为顶级, Error 和 Exception
 
Error :虚拟机错误,内存溢出,线程死锁
 
Exception : RuntimeException 为空指针异常,数组下标越界异常,算数异常,类型转换异常等,IO异常( IOException ),SQL异常( SQLException )。
 
异常处理,在 Java 中异常处理机制为: 抛出异常 和 捕捉异常
 
异常的描述:
 
class ExceptionDemo{
public static void main(String[] args){
int[] arr = new int[3];
System.out.println(arr[0]);
// 结果 为 0
System.out.println(arr[3]);
// 结果 为 图1
}
}
 
Java面向对象中的异常
 
System.out.println(arr[3]); 编译没问题,语法没有问题,编译完内存中没数组,运行的时候才在堆内存中开辟数组空间。 arr[3] 没有这个下标,所以在运行时找不到结果。
 
图1,表示数组下标越界异常, System.out.println(arr[3]); 运行时发生了异常为 ArrayIndexOutOfBoundException ,导致了程序无法运行,程序终结,不在执行。
 
错误的描述
 
class ExceptionDemo{
public static void main(String[] args){
int[] arr = new int[102410241024];
System.out.println(arr[0]);
// 结果 为 0
System.out.println(arr[3]);
// 结果 为 图1
}
}
 
Java面向对象中的异常
 
图2,表示运行时发生的错误,堆内存溢出。
 
异常和错误的区别
对于异常是由解决方案的,Java中提供了对应的处理机制,而错误没有,是没有办法去针对性的解决,唯一方法就是错误出现,修改代码。
 
异常的过程
在异常情况,运行时发生的问题,是数组下标越界异常,在异常抛出的问题为名称,内容,发生的位置等,多种信息进行了封装到对象中。
 
ArrayIndexOutOfBoundsException
 
public class ArrayIndexOutOfBoundsException extends IndexOutOfBoundsException
 
构造方法
 
ArrayIndexOutOfBoundsException()
ArrayIndexOutOfBoundsException(int index)
ArrayIndexOutOfBoundsException(String s);
 
ArrayIndexOutOfBoundsException 可以 new 对象,有构造方法,就可以 new 对象。创建对象,如果遇到问题就抛出, new ArrayIndexOutOfBoundsException(index) 。
 
如何抛出呢?利用关键字 throw ,出现异常,在 Java 虚拟机, jvm 中需要把问题抛出,给调用者 main ,主函数收到抛出的异常对象,但主函数没有办法处理,继续抛出调用者 jvm , jvm 收到异常问题后,将异常信息显示在屏幕上。
 
异常概述(意外、例外)
什么是异常呢?常见:
 
try-catch-finally
// try-catch-finally
public void method(){
try {
// 代码段
// 产生异常的代码段
}catch (异常类型 ex) {
// 对异常进行处理的代码段
}finally{
// 代码段
}
}
 
 
> throw
> throws
 
throws 声明时要进行抛出的异常
 
throw 要手动将产生的异常抛出
 
> public void method() throws Exception1,Exception2,...,ExceptionN {
>     // 产生异常代码
> }
// throw new IOException();
// 自己抛出的问题自己进行异常解决。
// 在抛出异常处,通过throws关键字标明异常类型
public void method() throws 异常类型{
// 代码 抛出
throw new 异常类型();
}
 
自定义异常
异常链

dawei

【声明】:九江站长网内容转载自互联网,其相关言论仅代表作者个人观点绝非权威,不代表本站立场。如您发现内容存在版权问题,请提交相关链接至邮箱:bqsm@foxmail.com,我们将及时予以处理。