11-异常
-
java中的异常机制: 异常是一个特殊的类.类型为java.lang.Exception 是指在程序运行过程中的一些不正常的事件,它会直接中断正在运行的程序
异常:
- InputMismatchException : 类型不匹配
- ArithmeticException : 算术异常
处理流程:
程序中预先设置好对付异常的处理办法–>遇到异常–>处理异常–>处理完毕之后,程序继续运行
-
java中的异常处理的关键字: 5个
-
捕获异常:
try: 执行可能产生的异常
catch: 捕获异常
finally: 异常处理完之后执行finally代码(无论是否发生异常,代码都会执行)
-
声明异常:
throws: 声明方法可能存在的异常
-
抛出异常:
throw: 手动抛出异常
-
组合格式:
- try - catch
- try - finally
- try - catch - finally
注意: try不可以单独使用
-
注意事项:
finally: 唯一不执行的情况 在遇到System.exit();时不执行
当try-catch中有return语句的时候:
try -> 产生异常对象->异常类型进行匹配->catch->finally–>return
return: 整个方法的结束
-
public class ExceptionDemo {
public static void main(String[] args) {
//创建Scanner 对象
Scanner input = new Scanner(System.in);
try {
System.out.println("请输入被除数:");
int num1 = input.nextInt();
System.out.println("请输入除数:");
int num2 = input.nextInt(); //new ArithmeticException
System.out.println(num1+"/"+num2+"="+(num1/num2));
} catch (InputMismatchException e) { //类型转换异常 //InputMismatchException e=new ArithmeticException
System.out.println("对不起,您需要输入整数哦~");
} catch (ArithmeticException e) { //类型转换异常 //InputMismatchException e=new ArithmeticException
System.out.println("除数不可以为零啊~~");
}finally{
//System.exit(0); //0的情况就像我们手动关机,除0以外,等于直接断电
System.out.println("这句话我永远都在......");
}
}
}
-
自定义异常:
- 定义一个类继承Exception
- 从父类中获取构造函数
自定义异常的好处, 更准确的去描述程序运行中产生的问题
public class GenderException extends Exception {
public GenderException() {//无参构造
super();
// TODO Auto-generated constructor stub
}
public GenderException(String message) { //有参构造
super(message);
// TODO Auto-generated constructor stub
}
}
-
throw: 手动抛异常
位置: 写在方法里
public class ThrowDemo {
private String gender;
public String getGender() {
return gender;
}
public void setGender(String gender) {
if("男".equals(gender)||"女".equals(gender)){
this.gender = gender;
}else{
//System.out.println("性别只能是男或者是女..");
try {
throw new GenderException("性别只能是男或者是女...");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} //Exception (String s)
}
}
public static void main(String[] args) {
//创建对象
ThrowDemo t = new ThrowDemo();
t.setGender("男");
}
}
-
声明方法可能存在的异常:
位置: 方法外,方法名之后
Exception分为量大类:
checkedException: 检查时异常 必须处理的异常:或try-catch或继续声明
RuntimeException : 运行时异常 可处理可不处理
注意事项:
1.如果throws后是exception或checkedException,要求调用处必须进行异常处理或try-catch或继续声明
2.如果throws后是RuntimeException 异常,方法的调用处
public class Throwssss {
public static void div(int num1,int num2) throws Exception { //声明异常
System.out.println(num1+"/"+num2+"="+(num1/num2)); // div();
}
public static void main(String[] args) throws Exception { //继续声明 交给java 虚拟机
div(10,0);
}
public static void div1(int num1,int num2) throws Exception { //声明异常
System.out.println(num1+"/"+num2+"="+(num1/num2)); // div();
div(12,2);
}
}