java——异常

1,异常体系
根类是object 下的Throwable
Throwable实现的接口:Serializable
Throwable的子类:Error,Exception
2,异常处理方案:
A:throws
B:try…catch…finally
3,实例代码:
public class ExceptionDemo {
public static void main(String[] args){
//throws throw形式
String prarm=null;
// method(prarm);
System.out.println("========================");
//try catch形式
/*
* 使用try catch形式请注意
*
*catch语句块可以写多个,多个catch语句块之间,可以是平级关系,也可以是继承关系,
* 只不过,如果是继承关系,需得先写子类,父类必须写在最后
* 程序会按顺序执行try语句块中的代码,当执行的语句有异常发生时,例如算数异常,那么
* 程序会跳转到catch语句块部分继续执行,并且会携带发生的异常类型,如果carch刚好有
* 算数异常分支,就执行该分支下的代码,然后再顺序执行其他的代码(不再执行catch分支)
* */
try{
int i=10;
int b=2;
int sum=i/b;
System.out.println(sum);
int [] array=new int[]{1,2,3};
System.out.println(array[2]);
}catch (NullPointerException ex){
System.out.println(“发生了空指针异常,我知道了”);
}catch (ArithmeticException ex){
System.out.println(“发生了算数异常,我知道了”);
}catch (ArrayIndexOutOfBoundsException ex){
System.out.println(“发生了数组越界异常,我知道了”);
}catch (RuntimeException ex){
System.out.println(“发生了运行时异常,我知道了”);
}catch (Throwable ex){
System.out.println(“我知道发生异常了,该做啥就做啥吧”);
}
System.out.println(“hello world”);
}
public static void method(String prarm)throws NullPointerException{
if(prarm == null){
System.out.println(“参数为空,请检查”);
throw new NullPointerException();
}
System.out.println(“world”);
int len=prarm.length();
System.out.println(“hello”);
}
}
4,常见的编译时异常与运行时异常
编译是异常:
SQLException
IOException
EOFException(读取文件达到文件结尾标志时,会发生)
FileNotFoundException
ClassNotFoundException
运行时异常:
ArithmeticException
ClassCastException
NoPointException
StringIndexOutOfBoundsException
ArrayIndexOutOfBoundsException

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值