Java中的异常大致分为两类:
1.Checked Exception :一定能够检测出来的异常,因此一定要需要处理。处理的方式有两种:继续往外抛,知道抛到JVM,这是一种消极的方法;另外是使用try catch.
2.Unchecked Exception :又叫做runtime exception,这一类型的异常在运行时才能发现,平常检测不出来。对于这一类型的异常,可以不作任何处理。
Error和Exception都是继承于Throwable。
解决方法1:继续向外抛,直到抛到JVM(JAVA 虚拟机);
import java.io.IOException;
public class ExceptionTest {
public void doSomething() throws IOException{
}
public static void main(String[] args) throws IOException{
ExceptionTest et = new ExceptionTest();
et.doSomething();
}
}
解决方法2:使用try-catch语句块
import java.io.IOException;
public class ExceptionTest {
public void doSomething() throws IOException{
}
public static void main(String[] args) {
ExceptionTest et = new ExceptionTest();
try
{
et.doSomething();
return;
}
catch(IOException ex)
{
}
finally
{
System.out.println("~~~~");
}
}
}
}
情况3:如果是runtime exception,则不需要对异常进行处理
import java.io.IOException;
public class ExceptionTest {
public void doSomething() throws ArithmeticException{
}
public static void main(String[] args) throws IOException{
ExceptionTest et = new ExceptionTest();
et.doSomething();
}
}