版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_34195441/article/details/86077400
1、一些异常类型
异常:编译时异常、运行时异常
运行时异常:程序在运行时,由于代码想出现的问题或者设备出现的问题而造成的运行时错误
运行时异常:nullpointerexception(空指针异常)、ClasscastException(类型转换异常)、 Indexoutofboundsexception(下标越界异常)、NumberFormatException(数据格式转换异常)、ArithmeticException(算术异常)
public class TestException {
public static void main(String[] args) {
/*
* String str="abc";
* 将字符串转为整型,字母串会报错,只能转换数字串
*/
String str="12";
//将字符串转换为integer
Integer num=Integer.parseInt(str);
int num2=Integer.valueOf(str);
num++;
//int类型的转化为字符串
String numstr=num.toString();
System.out.println(num+numstr);
}
}
2、异常处理
1)异常抓取
package com.hpu.exception;
/**
* 程序在运行时碰到错误会直接中断程序;try...catch:处理异常的一种方式,添加之后
* 当代码出现异常时,不会影响后续代码的执行
*
* try:一般存放可能会发生异常的代码
* catch:当出现异常时,打印异常的具体信息
* 当执行try中的代码时,只要执行到异常代码就直接跳到catch中
* @author Administrator
*
*/
/*
* main方法中统一使用try...catch处理异常,不能再向上抛出异常
* 被main方法调用的普通方法可以选择向main方法中抛出异常,或者在当
* 前方法中使用try...catch来抓取异常
*/
public class TestException3 {
public static void main(String[] args) {
int num1=2;
int num2=0;
try{
System.out.println("hahaha");
remove(num1,num2);
}catch(Exception e){
e.printStackTrace();
System.out.println("除数不能为0");
}
System.out.println("honghong");
}
//测试自定义异常,首先要建立自定义异常的类,这里为HpuException
private static void remove(int num1, int num2) throws HpuException{
// TODO Auto-generated method stub
if(num2==0){
throw new HpuException("来自大菜的警告");
}
}
/**系统定义的异常
* private static void remove(int num1, int num2)throws Exception{
// TODO Auto-generated method stub
//求两个数相除的结果
System.out.println(num1/num2);
}
*/
}
package com.hpu.exception;
//自定义异常类
public class HpuException extends Exception {
public HpuException(){
super();
}
public HpuException(String message){
super(message);
}
}
2)三种书写方式
package com.hpu.exception;
/**
* catch可以存在多个,catch不能存在try中不会触发的异常
* try...catch..finally、try..catch、try..finally;try或catch不能单独出现
* finally中的代码一定会执行,跟不加finally的区别:当catch或者try中有return关键字时,finally中的代码一定会执行
* @author Administrator
*
*/
public class TestException4 {
public static void main(String[] args) {
int num1=2;
int num2=0;
try{
System.out.println(num1/num2);
System.out.println("try~~~");
}catch(Exception e){
e.printStackTrace();
System.out.println("Catch~~~");
return;
}finally{
System.out.println("finally~~~");
}
}
}