ps:不會(huì)用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);//當(dāng)端口被占用此處出現(xiàn)檢查時(shí)異常
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
當(dāng)我們new ServerSocket時(shí)會(huì)有異常出現(xiàn)统翩,需要手動(dòng)解決仙蚜,
二.RuntimeException
例子:
package exception;
//基礎(chǔ)類
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;
//實(shí)現(xiàn)類
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());
}
}
輸出結(jié)果:
這個(gè)java.lang.NullPointerException的異常就是一個(gè)RuntimeException類的異常,在編譯時(shí)不會(huì)發(fā)現(xiàn)厂汗,當(dāng)程序運(yùn)行時(shí)就會(huì)出現(xiàn)錯(cuò)誤委粉,導(dǎo)致程序停止,需要我們在編寫時(shí)將其捕獲并處理娶桦。
改善后的代碼:
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送爸,并且不需要再類實(shí)現(xiàn)設(shè)計(jì)上花費(fèi)心思铛嘱,我們需要的知識(shí)異常名。
自定義類:
package exception;
public class AgeException extends Exception{
private String message;//異常信息
public AgeException(int age){
message = "年齡設(shè)置為:"+age+"不合適OА墨吓!";
}
public String toString() {
return message;
}
}
改進(jìn)setAge()方法,當(dāng)年齡不符合時(shí)拋出異常
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());
}
}
}
輸出結(jié)果: