异常
异常分为运行时异常和编译时异常。
运行时异常
RuntimeException在编译时不会发生异常,就是没有语法错误,但是在运行的过程中有严重的逻辑错误而导致的程序中断。
常见的运行时异常有
nullPointerExcption控制指针异常
ArrayIndexOfBaundsException数组越界异常
NumberFormatException数据格式异常
ArithmeticExcption计算异常
编译时异常
在程序设计中,编译时就发生的错误,但是执行时可能不发生错误,为了程序不报错可以执行,这一类错误需要进行相应的处理。
Error 不属于异常,至严重的问题,程序员无法处理
处理关键字
1:try{
程序可能出现异常的地方
}
2:catch{
用来捕获异常并作出处理
}
3:finally{
程序必须要处理的代码块,一般用来关闭物理资源
}
4:throw用于手动抛出异常 throw new XXXException("");
5:throws方法申明可能存在的而异常 throws XXXException
一个方法抛出的异常用throws关键字,调用者最上一层一定要处理,否则程序会中断
程序员手动抛出异常throw
手动抛出异常过程新建一个异常类,让他继承Exception或者RuntimeException类;在类中重写父类带参构造,在自己写的类中的构造方法或者setter方法中对属性做出限定,如果不满足这个限定就throw new 自己建立的这个异常类在可能出错的代码上加上try catch块 e.printStackTrace()就可以实现自定义异常了下面是我写的两个自定义异常类
//年龄越界异常
package com.it.exception;
/**
* @Date 2019/8/15 20:33
* @Created by hfh
* @Description TODO
*/
public class AgeException extends RuntimeException {
public AgeException(String message) {
super(message);
}
public AgeException(String message, Throwable cause) {
super(message, cause);
}
}
//性别输入有误异常
package com.it.exception;
/**
* @Date 2019/8/15 20:34
* @Created by hfh
* @Description TODO
*/
public class GenderException extends RuntimeException{
public GenderException(String message) {
super(message);
}
public GenderException(String message, Throwable cause) {
super(message, cause);
}
}
//限定代码
package com.it.exception;
/**
* @Date 2019/8/15 20:29
* @Created by hfh
* @Description TODO
*/
public class Person {
private String gender;
private int age;
public Person() {
}
//构造函数对性别年龄范围作限定,如果越界,就抛出异常
public Person(String gender, int age) {
if (gender.equals("男")||gender.equals("女")||gender.equals("male")||gender.equals("female")) {
this.gender = gender;
}else {
throw new GenderException("性别输入有误");
}
if (age<120&&age>0){
this.age = age;
}else {
throw new AgeException("年龄超出范围");
}
}
public String getGender() {
return gender;
}
//setter 方法对性别年龄做限定,如果越界就抛出相应的异常
public void setGender(String gender) {
if (gender.equals("男")||gender.equals("女")||gender.equals("male")||gender.equals("famale")) {
this.gender = gender;
}else {
throw new GenderException("性别输入有误");
}
}
public int getAge() {
return age;
}
public void setAge(int age) {
if (age<120&&age>0){
this.age = age;
}else {
throw new AgeException("年龄超出范围");
}
}
public void print(){
System.out.println(this.age+" "+this.gender);
}
}
//测试代码
package com.it.exception;
/**
* @Date 2019/8/15 20:38
* @Created by hfh
* @Description TODO
*/
public class PersonTest {
public static void main(String[] args) {
Person person = new Person("男",12);
person.print();
try {
person.setAge(456);
} catch (Exception e) {
e.printStackTrace();
}
//person.setGender("djkffl");
person.print();
}
}
//结果
com.it.exception.AgeException: 年龄超出范围
at com.it.exception.Person.setAge(Person.java:50)
at com.it.exception.PersonTest.main(PersonTest.java:13)
12 男
12 男