[java]源码详解java异常处理
java异常处理,原理、理论很多很多,还是需要一点点去理解,去优化。这里现贴出一下,只为形象的感知java异常处理方式。
1.try catch
[java]
public class testtrycatch {
public static void try() {
int i = 1 / 0;
try {
} catch (exception e) {
e.printstacktrace();
}
}
public static void main(string[] args) {
testtrycatch.try();
}
}
try catch是java程序员常常使用的捕获异常方式,很简单,不赘述了,上述程序执行结果:
[plain]
exception in thread "main" java.lang.arithmeticexception: / by zero
at com.jointsky.exception.testtrycatch.try(testtrycatch.java:6)
at com.jointsky.exception.testtrycatch.main(testtrycatch.java:15)
2.throws exception
[java]
public class testthrows {
public static void throws() throws exception {
try {
int i = 1 / 0;
} catch (exception e) {
throw new exception("除0异常:" + e.getmessage());
}
}
public static void main(string[] args) throws exception {
//注意:main函数若不加throws exception 编译不通过
testthrows.throws();
}
}
这个例子主要理解一下throws和throw这两个关键字的区别,执行结果:
[plain]
exception in thread "main" java.lang.exception: 除0异常:/ by zero
at com.jointsky.exception.testthrows.throws(testthrows.java:12)
at com.jointsky.exception.testthrows.main(testthrows.java:20)
3.自写异常类
[java]
public class diyexception {
public static void testdiy() {
system.out.println("this is diyexception");
}
}
[java]
public class testextendsexception extends diyexception {
public static void throws() throws exception {
try {
int i = 1 / 0;
} catch (exception e) {
diyexception.testdiy();
}
}
public static void main(string[] args) {
// 注意:不加try{}catch(){} 编译不通过
try {
testextendsexception.throws();
} catch (exception e) {
// todo auto-generated catch block
e.printstacktrace();
}
}
}
异常处理也可自行编写,上述程序执行结果:
[plain]
this is diyexception
p.s.
问题总会莫名其妙的出来,很多东西,还是需要一点点的去积累。这需要一个过程,耐心点,多准备准备,等莫名其妙的问题出来的时候,就不那么狼狈了。