java基礎(內存、異常) 參考資料馬士兵j2se教程
1、內存(見(jiàn)附圖)
2、異常
1)異常類(lèi)層次圖
Throwable
|
|————|
Error Exception
|
|—————————————|—————————|——————————|
ClassNotFoundException IOException .................. RuntimeException
|
|—————————————|—————————|———————|
ArithmeticException ................. IndexOutOfBoundsException
- Error :虛擬機錯誤,程序處理不了
- Exception :程序可以處理的。
- RuntimeException:經(jīng)常出的錯誤??梢圆惶幚恚ú淮惓#┤鐣?huì )不會(huì )數組越界啊、算數中除數可能會(huì )是零。一般可以不處理。編譯也能通過(guò)。
- 除RuntimeException以外的Exception:必須處理,如上面的IOException,要不編譯通不過(guò)。一般就是jdk幫助文檔中方法后加了throws 的方法。
2)內存的處理
- 拋異常。(見(jiàn)附圖)
-
- 當拋出多個(gè)異常時(shí),先逮小異常,再逮大異常。要不編譯通不過(guò)。
- 使用自定義異常,可以從Exception繼承(必須逮)或從RuntimeException繼承(可以不逮)。
- 注意:繼承某個(gè)原來(lái)拋出異常的類(lèi)時(shí),子類(lèi)一定要拋出一模一樣的異?;蛘吒纱嗖粧仯╦ava設計的比較奇怪吧不拋可以),拋一個(gè)比父類(lèi)的異常范圍大的異常,或者拋一個(gè)范圍比父類(lèi)小的,或比父類(lèi)多的異常都不行。
- 自定義異常類(lèi)舉例
-
- public class MyFirstException extends Exception {
- public MyFirstException() {
- super();
- }
- public MyFirstException(String msg) {
- super(msg);
- }
- public MyFirstException(String msg, Throwable cause) {
- super(msg, cause);
- }
- public MyFirstException(Throwable cause) {
- super(cause);
- }
- }
- public class MyFirstException extends Exception {
- public MyFirstException() {
- super();
- }
- public MyFirstException(String msg) {
- super(msg);
- }
- public MyFirstException(String msg, Throwable cause) {
- super(msg, cause);
- }
- public MyFirstException(Throwable cause) {
- super(cause);
- }
- }
public class MyFirstException extends Exception { public MyFirstException() { super(); } public MyFirstException(String msg) { super(msg); } public MyFirstException(String msg, Throwable cause) { super(msg, cause); } public MyFirstException(Throwable cause) { super(cause); } } -
-
-
-
-
-
- public class TestMyException {
- public static void firstException() throws MyFirstException{
- throw new MyFirstException("\"firstException()\" method occurs an exception!");
- }
-
- public static void main(String[] args) {
- try {
- TestMyException.firstException();
- }
- catch (MyFirstException e1){
- System.out.println("Exception: " + e1.getMessage());
- e1.printStackTrace();
- }
- }
-
-
-
-
-
- public class TestMyException {
- public static void firstException() throws MyFirstException{
- throw new MyFirstException("\"firstException()\" method occurs an exception!");
- }
-
- public static void main(String[] args) {
- try {
- TestMyException.firstException();
- }
- catch (MyFirstException e1){
- System.out.println("Exception: " + e1.getMessage());
- e1.printStackTrace();
- }
- }
/** * 自定義異常類(lèi)的使用 * @author new * */ public class TestMyException { public static void firstException() throws MyFirstException{ throw new MyFirstException("\"firstException()\" method occurs an exception!"); } public static void main(String[] args) { try { TestMyException.firstException(); } catch (MyFirstException e1){ System.out.println("Exception: " + e1.getMessage()); e1.printStackTrace(); } }