一.异常的基本概念:
1.异常是错误,运行时异常。
2.抛异常,创建一个错误对象,把错误对象丢出来。
3.捕获异常,默认由JVM来把错误信息进行捕获,打印出来,JVM会终止程序的执行。
二.异常的分类:
RuntimeException:运行时异常,一般不手动处理。
其他Exception必须经过手动处理。
Error:一般指系统级错误。
三.异常的处理:
try…catch…
package obb;
public class test {
public static void main(String[] args) {
try {
int a=1/0;
System.out.println(a);
}catch (Exception e){
e.printStackTrace(); //可以看到哪里出错
System.out.println("计算结果格式非法,重新输入");
}finally {
System.out.println("我是finally");
}
}
}
finally:无论最后是不是异常,finally都会输出。
package obb;
public class test {
public static void chu(int a,int b) throws Exception{ //告诉外面我要仍一个异常
if(b==0) {
throw new Exception("0不能做除数");//真正向外抛出一个异常
}else {
System.out.println(a/b);
}
}
public static void main(String[] args) throws Exception{
chu(1,0);
}
}
四.自定义异常:
throws Exception: 抛出异常,谁调用谁处理。
package obb;
public class Person {
String name;
String gender;
public Person(String name, String gender) {
super();
this.name = name;
this.gender = gender;
}
}
package obb;
public class Zaotangzi {
public void nan(Person p) throws genderException{
if(p.gender=="男")
System.out.println("欢迎光临");
else {
throw new genderException("性别不对,这里是男澡堂");
}
}
}
抛出异常。
正常