java异常

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
      
      
import java.io.* ;
public class ExceptionTest {
public static void main ( String args []){
try {
int a [] = new int [ 2 ];
System . out . println ( "Access element three :" + a [ 3 ]); //数组只有2个元素,访问第三个时会发生ArrayIndexOutOfBoundsException异常
} catch ( ArrayIndexOutOfBoundsException e ){
System . out . println ( "Exception thrown :" + e );
}
System . out . println ( "Out of the block" );
}
}

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" );
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值