1. java所有异常分类
Exception
│
├─ RuntimeException
│ │
│ ├─ NullPointerException
│ │
│ ├─ IndexOutOfBoundsException
│ │
│ ├─ SecurityException
│ │
│ └─ IllegalArgumentException
│ │
│ └─ NumberFormatException
│
├─ IOException
│ │
│ ├─ UnsupportedCharsetException
│ │
│ ├─ FileNotFoundException
│ │
│ └─ SocketException
│
├─ ParseException
│
├─ GeneralSecurityException
│
├─ SQLException
│
└─ TimeoutException
2. 捕获异常
public static void main(String[] args) {
try {
process1();
process2();
process3();
} catch (IOException e) {
System.out.println(e);
} catch (NumberFormatException e) {
System.out.println(e);
}
}
2.1. 捕获异常catch 的顺序
public static void main(String[] args) {
try {
process1();
process2();
process3();
} catch (IOException e) {
System.out.println("IO error");
} catch (UnsupportedEncodingException e) {
System.out.println("Bad encoding");
}
}
改正:
public static void main(String[] args) {
try {
process1();
process2();
process3();
} catch (UnsupportedEncodingException e) {
System.out.println("Bad encoding");
} catch (IOException e) {
System.out.println("IO error");
}
}
2.2. finally语句
public static void main(String[] args) {
try {
process1();
process2();
process3();
} catch (UnsupportedEncodingException e) {
System.out.println("Bad encoding");
} catch (IOException e) {
System.out.println("IO error");
} finally {
System.out.println("END");
}
}
3. 抛出异常
NumberFormatException ne = new NumberFormatException();
throw ne;
// 简洁写法
throw new NumberFormatException();
class GoogleAbnor {
public void googleAbnor(String s) throws NumberFormatException {
// NumberFormatException ne = new NumberFormatException();
// throw ne;
if (s == null) {
throw new NumberFormatException();
} else {
System.out.println("String fine");
}
}
}
class Abnor {
public void abnor() {
GoogleAbnor ga = new GoogleAbnor();
ga.googleAbnor(null);
}
}
public class AbnormalLearn {
public static void main(String[] args) {
GoogleAbnor gab = new GoogleAbnor();
try {
gab.googleAbnor("Hello");
} catch (Exception e) {
System.out.println("Catch NumberFormatException");
e.printStackTrace();
}
Abnor ab = new Abnor();
ab.abnor();
}
}
------------------------------------------------------------------------------------------------
执行结果:可以看到已经抛出了我们的异常
String fine
Exception in thread "main" java.lang.NumberFormatException
at com.zhbi.source.GoogleAbnor.googleAbnor(AbnormalLearn.java:10)
at com.zhbi.source.Abnor.abnor(AbnormalLearn.java:21)
at com.zhbi.source.AbnormalLearn.main(AbnormalLearn.java:38)
Java Result: 1