异常的常见语法
java下有一个类叫做Throwable,其子类有Exception和Error,Exception可以捕获并补救,但Error无法补救。
Exception下有很多子类,比如NullPointerException,SQLException,IOException等等。
public class Test{
try{
String str="hello";
System.out.println(str);
}catch(Exception ex){
ex.printStackTrace();
}
}
throws
一般表示该方法有使用风险,在使用该方法的时候要进行一定的操作
方法一:在使用该方法时用try-catch包围
class A {
public void hi() throws IOException{
System.out.println("你好");
}
}
public class Test{
public static void main(String[] args){
try{
A a=new A();
a.hi();
}catch(IOException ex){
ex.printStackTrace();
}
}
}
方法二:将异常抛到上一层
class A {
public void hi() throws IOException{
System.out.println("你好");
}
}
public class Test{
public static void main(String[] args) throws IOException{
A a=new A();
a.hi();
}
}
throw
表示该方法会造成不可挽回的后果,throw在方法主体中写,举个例子
class A {
public void hi() {
System.out.println("你好");
try{
throw new IOException;
}catch(IOException ex){
}
}
}
public class Test{
public static void main(String[] args) throws IOException{
A a=new A();
a.hi();
}
}
也可以这么解决
class A {
public void hi() throws Exception{
System.out.println("你好");
throw new IOException;
}
}
public class Test{
public static void main(String[] args) throws Exception{
A a=new A();
a.hi();
}
}