异常就是程序在运行过程中出现的异常事件,会中断事件的正常运行。
在java程序执行过程中,如果出现异常事件,就会生成一个异常对象,并把这个对象传给Java run time,并抛出异常。
java中,异常对应的类是Throwable,或者是它的子类,它的子类有两种,一为java.lang.Error,另一种为java.lang.Exception. Error类一般为JVM的错误等,会直接中断程序,通常情况下不会捕获异常;Exception类通常需要java来处理。
异常的关键字有throw,throws,try,catch, finally
public class Exception1 {
public static void main(String[] args) throws IOException {
int div = 0;
int result = 10 / div;
System.out.println("result is " + result);
FileInputStream fileObject = new FileInputStream("input.java");
int len = fileObject.read();
System.out.println(len);
FileNotFoundException exceptionObj = new FileNotFoundException();
throw exceptionObj;
}
}
FileInputStream fileObject = new FileInputStream("input.java"); 这句话会抛出一个FileNotFoundException,你可以通过throws来抛出,或者try catch来捕获。
fileObject.read(); 会抛出IOexception。
int result = 10 / div; 会有ArithmeticException,但是在编译的时候,系统不会抛出异常,而是在运行期出错。
throw exceptionObj; 会抛给调用他的方法,一级一级的向上找,被main()处理。s
Demo2:
public class Exception2 {
public static void main(String[] args) {
try {
throw new Exception("exception");
} catch (Exception e) {
// TODO Auto-generated catch block
System.out.println("catch exception");
System.out.println(
"exception get message is "
+ e.getMessage());
System.out.println(
"exception to string is " +
e.toString());
System.out.println(
"exception print stract trace is ");
e.printStackTrace();
}
}
}
try{}catch{}finally{}, try是用来限制程序块中有可能出现异常,catch会来捕获异常。finally是异常的统一出口,无论是否发生异常,最终都要执行finally。
Demo3 自定义异常:
public static void exceptionThrow() throws newException {
System.out.println("Throw exception from exceptionThrow");
throw new newException();
}
public static void anotherThrow() throws newException {
System.out.println("Throw exception form anotherThrow");
throw new newException("str");
}
public static void main(String[] args) {
try {
System.out.println("one exception throws out:");
exceptionThrow();
} catch (newException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
System.out.println("another exception throws out: ");
anotherThrow();
} catch (newException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class newException extends Exception {
public newException(){
}
public newException(String str){
super(str);
}
如果程序中有多个catch,会按照捕获的先后顺序执行,所以要catch一些特殊的异常,然后在catch那些大的异常