一:观察异常
在一上一节我们讲解了常见的异常类型,这次可我们通过代码来观察这些异常是如何出现的。
DEMO:算术异常
![](https://upload-images.jianshu.io/upload_images/19872357-387b1ca278e21d2a.png?imageMogr2/auto-orient/strip|imageView2/2/w/720/format/webp)
此时出现的是算术异常。
DEMO:数组越界异常
![](https://upload-images.jianshu.io/upload_images/19872357-78e52e75f3f3c520.png?imageMogr2/auto-orient/strip|imageView2/2/w/720/format/webp)
发现了出现异常的之后的代码也执行了
DEMO:类型转换异常
![](https://upload-images.jianshu.io/upload_images/19872357-f3871ee02c23b0c9.png?imageMogr2/auto-orient/strip|imageView2/2/w/720/format/webp)
DEMO:无属性异常
![](https://upload-images.jianshu.io/upload_images/19872357-c98047816d04a47a.png?imageMogr2/auto-orient/strip|imageView2/2/w/720/format/webp)
![](https://upload-images.jianshu.io/upload_images/19872357-460816b905c3ad03.png?imageMogr2/auto-orient/strip|imageView2/2/w/720/format/webp)
这个代码我们使用到了反射的知识,你暂时看见这个异常就行了,不理解没关系,因为反射是我们第四章的内容。
DEMO:无方法异常
![](https://upload-images.jianshu.io/upload_images/19872357-2c3ceb1801808e98.png?imageMogr2/auto-orient/strip|imageView2/2/w/720/format/webp)
![](https://upload-images.jianshu.io/upload_images/19872357-aabbf3d55538ffee.png?imageMogr2/auto-orient/strip|imageView2/2/w/720/format/webp)
这个代码我们使用到了反射的知识,你暂时看见这个异常就行了,不理解没关系,因为反射是我们第四章的内容。
DEMO:空指向异常
![](https://upload-images.jianshu.io/upload_images/19872357-ff987d321441883e.png?imageMogr2/auto-orient/strip|imageView2/2/w/720/format/webp)
![](https://upload-images.jianshu.io/upload_images/19872357-a5c525697955a780.png?imageMogr2/auto-orient/strip|imageView2/2/w/720/format/webp)
●访问一个空对象的方法或者属性
●访问了-一个值为null的数组的长度时候会出现该异常
DEMO:数字格式化异常
![](https://upload-images.jianshu.io/upload_images/19872357-d20bd85067abbee6.png?imageMogr2/auto-orient/strip|imageView2/2/w/720/format/webp)
![](https://upload-images.jianshu.io/upload_images/19872357-07a381ec98023d02.png?imageMogr2/auto-orient/strip|imageView2/2/w/720/format/webp)
这种异常是将一个字符串类型的数据转换一个数字类型的数据时候可能出现该异常。
DEMO:类加载异常
![](https://upload-images.jianshu.io/upload_images/19872357-ee652b7bd5e5a3dc.png?imageMogr2/auto-orient/strip|imageView2/2/w/720/format/webp)
![](https://upload-images.jianshu.io/upload_images/19872357-a545559103ae5004.png?imageMogr2/auto-orient/strip|imageView2/2/w/720/format/webp)
这个demo也要使用到反射的知识,你暂时不需要完全明白,但是你要知道程序要运行那么加载器要将需要的class加载内存中。
上面的demo中异常在开发中你会经常发现,比如说你要使用到第三方的jar,可能没有下载到就会出现这样的异常。
有完整的Java初级,高级对应的学习路线和资料!专注于java开发。分享java基础、原理性知识、JavaWeb实战、spring全家桶、设计模式、分布式及面试资料、开源项目,助力开发者成长!
欢迎关注微信公众号:码邦主