throw 一旦执行异常,下面的程序就会立马停止,
try 捕获异常,还会进行执行以下代码
public class ThrowDemo {
public static void main(String[] args) {
int index=-1;
int[] arr={1,2,3,4,5};
printThrow(arr,index);
}
private static void printThrow(int[] arr, int index) {
//等效:于Objects.requireNonNull(arr);
if (arr==null){
throw new NullPointerException();
}
if(index<0||index>arr.length-1){
throw new ArrayIndexOutOfBoundsException();
}
}
}
自定义异常处理类
public class ThrowDemo {
public static void main(String[] args) throws IOException {
fileExit("D:\\03.txt");
}
public static void fileExit(String pathFile) throws IOException {
File file = new File(pathFile);
if(!file.exists()){
throw new FileNotFoundException("传递的文件路径不对");
}
if (pathFile.endsWith(".txt")){
throw new IOException("文件名的后缀不对");
}
}
}
try…catch()
public static void main(String[] args) {
try {
fileExit("D:\\02.txt");
}catch (IOException e){
System.out.println("程序出现异常");
}finally {
System.out.println("程序执行结束");
}
System.out.println("打印");
}
public static void fileExit(String pathFile) throws IOException {
File file = new File(pathFile);
if(!file.exists()){
throw new FileNotFoundException("传递的文件路径不对");
}
if (pathFile.endsWith(".txt")){
throw new IOException("文件名的后缀不对");
}
}
throwable得到异常的结果
public class ThrowDemo {
public static void main(String[] args) {
try {
fileExit("D:\\022.txt");
}catch (IOException e){
//打印自定义信息
System.out.println(e.getMessage());
//打印基本异常
System.out.println(e);
//打印异常具体信息
e.printStackTrace();
}
}
public static void fileExit(String pathFile) throws IOException {
File file = new File(pathFile);
if(!file.exists()){
throw new FileNotFoundException("传递的文件路径不对");
}
if (pathFile.endsWith(".txt")){
throw new IOException("文件名的后缀不对");
}
}
}