7.1 异常的基本概念:
1.如果不对异常进行处理,一旦出现异常程序就立刻退出
2.关于计算机的两大“杀手”,一是断电 二是除数为0
3.异常处理格式:
try{
可能出现异常的句子
}catch(异常类 异常对象){
异常处理语句
}[catch(){}
catch(){
......}]
[finally{
一定会运行的程序
}
]
Java中所有捕获范围小的异常必须放在捕获大的之前Exception是最大的异常范围
7.2 throws 与 throw 关键字
1. throws 关键字的使用:
在定义一个方法的时候可以使用throws关键字声明,此方法不处理异常而将异常留给方法的调用处处理
格式:public 返回值类型 方法名称 (参数列表) throws 异常类{}
2. throw 关键字发作用:
可以直接使用throw关键字抛出一个异常,抛出时直接异常类的实例化对象。(手动抛出异常)
throw不会单独使用
3 范例 ——throw与throws的应用
//计算器
package Exception;
import java.util.Scanner;
public class ThrowDemo02 {
public static void main(String[] args) {
Math1 m=new Math1();
Scanner sc=new Scanner(System.in);
try {
System.out.println("除法操作:"+m.div(sc.nextInt(),sc.nextInt()));
}catch (Exception e){
System.out.println("异常产生:"+e);
}
}
}
class Math1{
public int div(int i,int j)throws Exception{
System.out.println("计算开始");
int temp=0;
try {
temp=i/j;
}catch (Exception e) {
throw e;
}finally {
System.out.println("计算结束");
}
return temp;
}
}
7.3 Exception 类 与 Runtime Exception 类
Exception—— Runtime Exception —— Illegal Argument Exception—— Number Format Exception
-
Exception 在程序中必须使用try......catch
-
Runtime Exception 可以不使用try......catch 但异常将由 J V M 处理
-
Runtime Exception是Exception的子类
7.4 自定义异常类
//自定义异常类
package Exception;
import java.util.SortedMap;
public class DefaultException {
public static void main(String[] args) {
try {
throw new MyException("自定义异常");
}catch (Exception e){
System.out.println(e);
}
}
}
class MyException extends Exception{
public MyException(String msg){//接收异常信息
super(msg);//调用父类构造方法
}
}
7.5 断言
1.断言就是肯定某个结果的返回值是正确的,如果返回值是错误的,则通过断言检查肯定会提示错误信息
2.格式:
assert boolean 表达式;
assert boolean 表达式 :详细的信息
package Exception;
public class Text {
public static void main(String[] args) {
int x[]={1,2,3};
assert x.length==0;
}
}
结果:
Exception in thread "main" java.lang.AssertionError
at Exception.Text.main(Text.java:6)