java的异常种类分析
java--异常--种类: 用户输入错误数据、文件打开不存在、网络连接丢失、JVM已经耗尽内存、存在空值进行操作
java异常分哪些: 检查异常/checked exception-------检查异常通常是用户错误,程序员并不可预见的问题
运行异常/runtimeexception/uncheckedexception----运行时异常时本来可以由程序避免的异常
错误/error-----无法处理的异常
运行时的异常都有哪些错误: 常见的RuntimeException包括NullPointerException、IndexOutOfBoundsException、IllegalArgumentException等。
运行时的异常都有哪些错误: 常见的非RuntimeException包括IOException、SQLException等。
java异常如何捕获
1.捕获的方法是使用try/catch关键字。将可能产生异常,并且需要捕获的代码块使用try/catch围绕,如果产生了异常即可捕获到,将直接中断try代码块,同时执行catch代码块。
try/catch中的代码被称为受保护的代码(Protected code)。
实例
1 2 3 4 5 6 7 8 9 10 11 12 13 |
|
2.如果受保护的代码发生了异常,该异常被抛出到第一个catch块。如果异常的数据类型与ExceptionType1匹配,它就会被第一个catch捕获。如果不是,则该异常传递到第二个catch语句
import java.io.* ;public class ExceptionTest {public static void main ( String args []){try {FileInputStream file = new FileInputStream ( "/usr/test" );byte x = ( byte ) file . read ();} catch ( IOException i ) {System . out . println ( "IOException thrown :" + i );} catch ( NullPointerException f ) {System . out . println ( "NullPointerException thrown :" + f );}System . out . println ( "catch" );}}