认识异常
1.异常是导致程序中断运行的一种指令流,如果不对异常进行正确处理,则可能导致程序的中断执行,造成不必要的损失.
2.异常范例
class Exc {
int i = 10;
}
public class ExceptionDemo01 {
public static void main(String[ ] args) {//主方法
int a =10;//定义一个整型变量并初始化
int b = 10;
int temp = a/b;
System.out.println(temp);//输出异常
}
}
处理异常
1.异常格式
try {
异常语句
}catch(Exception e) {
}finally{
一定会执行的代码
}
捕获异常
class Exc {
inta =10;
int b = 10;
}
public class ExceptionDemo01 {
public static void main(String[ ] args) {
int temp = 0;
Exc e = null;
e = new Exc();
temp = e.a/e.b;
System.out.println(temp);
System.out.prinln("程序推出")
同时加多个catch语句模块,进行多个语句处理
package spzy;
public class ExceptionDemo1 {
class Exc {
int a = 10;
int b = 0;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int temp = 0;
Exc e = null;
//e =new Exc();
try {
temp = e.a/e.b;
System.out.println(temp);
}catch (NullPointerException e2) { //空指针异常
System.out.println("空指针异常:" +e2);//输出异常数据
}catch (ArithmeticException e2) { //算数异常
System.out.println("算数异常:" +e2);
//加finally不论是否发现异常都会成功推出
}finally {
System.out.println("程序推出");
}
}
}
常见异常
1、数组越界异常:ArrayIndexOutOfBoundsException
2、数字格式化异常:NumberFormatException
3、算数异常:ArithmeticException
4、空指针异常:NullPointerException
throws关键字
1、在定义一个方法的时候可以使用throws关键字声明,使用throws声明的方法表示此方法不处理异常,抛给方法的调用者处理。
2、格式:
public void tell() throws Exception{}
package spzy;
public class ExceptionDemo02 {
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
tell(10,0);
}catch(Exception e) { //异常捕获
System.out.println(e);
}
}
public static void tell(int i,int j) throws ArithmetivException{ //抛出异常
int temp = 0;
temp = i/j;
System.out.println(temp);
}
}
throw关键字
1、throw关键字抛出的
package spzy;
public class ExceptionDemo02 {
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
throw new Exception("实例化异常对象");//throw抛出
}catch(Exception e) { //异常捕获
System.out.println(e);//输出抛出异常
}
}
}
时候直接抛出异常类的实例化对象即可
自定义异常
1、自定义异常直接继承Exception就可以完成自定义异常
package spzy;
class MyException extends Exception{
public MyException(String msg) { //为传输输入参数
super(msg); //通过super来调用Exception里的错误传递
}
}
public class ExceptionDemo3 {
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
throw new MyException("自定义异常"); //抛出自己的异常
}catch (MyException e) {
System.out.println(e);//输出自定义异常
}
}
}