throw new NullPointerException();
//利用try-catch-finally块处理
public static void main(String[] args) {
try {
throw new MyException();
} catch (MyException e) {
e.printStackTrace();
}finally{
//do something
}
}
//抛给上层函数
public static void main(String[] args) throws MyException {
throw new MyException();
}
既然要抛出一个new的异常,那么就需要有异常类供我们new。这个异常类必须继承自Throwable类。
Throwable
|-------------Error
|-------------Exception
|-----------------RuntimeException
|-----------------其他Exception
public static void main(String[] args) {
try {
throw new MyException();
} catch (MyException e) {
e.printStackTrace();
/*
Exception in thread "main" java.lang.NullPointerException: / by zero //异常类名称和描述信息
at my_exception.Calculate.mod(Calculate.java:6) //异常出现时的系统栈情况
at my_exception.Main.main(Main.java:7)
*/
}finally{
//do something
}
}
public static void main(String[] args) throws MyException {
throw new MyException();
}
public static void main(String[] args) throws FileNotFoundException {
File file=new File("hello");
try {
FileInputStream fileInputStream=new FileInputStream(file);
} catch (FileNotFoundException e) {
//do something
throw e; //捕获到后重新抛出
}finally {
}
}
要了解catch与finally块的作用必须先了解这两个代码块分别在什么情况下进行。
public static void main(String[] args) {
File file=new File("hello");
try {
FileInputStream fileInputStream=new FileInputStream(file);
} catch (FileNotFoundException e) {
for (StackTraceElement s:e.getStackTrace())
System.out.println(s.getMethodName());
}finally {
}
}
public static void main(String[] args) {
File file=new File("hello");
try {
FileInputStream fileInputStream=new FileInputStream(file);
/*
打开文件后要执行的操作继续包在try-catch-finally块中
*/
try {
//打开文件后要执行的操作
}catch (Exception e){
}finally {
//资源的释放,文件的关闭在此处进行
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}finally {
//不要在此处关闭文件,因为执行此处时可能会是打开文件失败,这样就无需释放资源
}
}
(关于异常什么情况下该使用,笔者还没有较深的理解,欢迎大家向笔者提建议。同时笔者也会在以后继续补充)