简单处理
try {
String a = "123a";
int i = Integer.valueOf(a);
} catch (Exception e) {
e.printStackTrace();
}
throws和throw关键字
throws
表示当前方法不处理异常,而是交给方法的调用出去处理
throw
表示直接抛出一个异常
package com.little;
public class Demo1 {
static void demoThrows() throws Exception{
String a = "123a";
int i = Integer.valueOf(a);
}
public static void main(String[] args) {
try {
demoThrows();
} catch (Exception e) {
e.printStackTrace();
}
}
}
output
java.lang.NumberFormatException: For input string: "123a"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:580)
at java.lang.Integer.valueOf(Integer.java:766)
at com.little.Demo1.demoThrows(Demo1.java:6)
at com.little.Demo1.main(Demo1.java:10)
抛出异常示例:
package com.little;
public class Demo1 {
static void demoThrow() throws Exception{
throw new Exception("出错了.");
}
public static void main(String[] args) {
try {
demoThrow();
} catch (Exception e) {
e.printStackTrace();
}
}
}
java.lang.Exception: 出错了.
at com.little.Demo1.demoThrow(Demo1.java:5)
at com.little.Demo1.main(Demo1.java:9)
Exception和RuntimeException区别
Exception
是检查型异常,在程序中必须使用try...catch
进行处理
RuntimeException
是非检查型异常,例如NumberFormatException
,可以不使用try...catch
进行处理,如果发生异常,则异常由JVM
进行处理
RuntimeException
最好也用try...catch
捕获
自定义异常
public class CustomException extends Exception{
public CustomException(String message) {
super(message);
}
}
public class Demo1 {
private static void test() throws CustomException {
throw new CustomException("自定义异常");
}
public static void main(String[] args) throws CustomException {
test();
}
}
Exception in thread "main" com.little.CustomException: 自定义异常
at com.little.Demo1.test(Demo1.java:6)
at com.little.Demo1.main(Demo1.java:10)