ps:不会用markdown 代码框,排版有问题请见谅!
一.checkedException
package exception;
import java.io.IOException;
import java.net.ServerSocket;
public class CheckExceptionTest {
public static ServerSocket ss = null;
public static void doEx1(){
try {
ss = new ServerSocket(8888);//当端口被占用此处出现检查时异常
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
当我们new ServerSocket时会有异常出现,需要手动解决,
二.RuntimeException
例子:
package exception;
//基础类
public class Person {
private int age;
private String name;
public Person(int age, String name) {
super();
this.age = age;
this.name = name;
}
public Person() {
super();
// TODO Auto-generated constructor stub
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
package exception;
//实现类
public class ExceptionTest {
public static void main(String[] args) {
Person p = new Person();
String personName = null;
p.setName(personName);
System.out.println(p.getName().toString());
}
}
输出结果:
这个java.lang.NullPointerException的异常就是一个RuntimeException类的异常,在编译时不会发现,当程序运行时就会出现错误,导致程序停止,需要我们在编写时将其捕获并处理。
改善后的代码:
package exception;
public class ExceptionTest {
public static void main(String[] args) {
Person p = new Person();
try {
String personName = null;
p.setName(personName);
System.out.println(p.getName().toString());
} catch (NullPointerException e) {
System.out.println("姓名不能为空!!!");
}
}
}
输出:
三.自定义异常
上面的例子中,age属性需要判断大于0并且小于100,正常人的年龄,但是java类并没有为我们提供AgeException,所以需要自定义,自定义异常必须继承自Exception,并且不需要再类实现设计上花费心思,我们需要的知识异常名。
自定义类:
package exception;
public class AgeException extends Exception{
private String message;//异常信息
public AgeException(int age){
message = "年龄设置为:"+age+"不合适!!";
}
public String toString() {
return message;
}
}
改进setAge()方法,当年龄不符合时抛出异常
public void setAge(int age) {
if(age<=0 && age>=120){
try {
throw new AgeException(age);
} catch (AgeException e) {
System.out.println(e.toString());
}
}else{
this.age = age;
}
}
测试代码:
public class ExceptionTest {
public static void main(String[] args) {
Person p = new Person();
Person p1 = new Person();
try {
p1.setAge(120);
} catch (Exception e) {
System.out.println(e.toString());
}
try {
p.setAge(60);
System.out.println("正确年龄:"+p.getAge());
} catch (NullPointerException e) {
System.out.println(e.toString());
}
}
}
输出结果: