java中异常处理类throw抛出异常,try catch捕获异常

Posted weixin_ancenhw

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java中异常处理类throw抛出异常,try catch捕获异常相关的知识,希望对你有一定的参考价值。

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("文件名的后缀不对");
        

    


以上是关于java中异常处理类throw抛出异常,try catch捕获异常的主要内容,如果未能解决你的问题,请参考以下文章

java中异常处理类throw抛出异常,try catch捕获异常

Java异常 Exception类及其子类

java中throw抛出的异常一定要用相应的catch块处理吗

Java异常处理中关键字throws,throw,try,catch,finally分别代表啥意义?在try块中可以抛出异常吗

Java面试题22 JAVA语言如何进行异常处理,关键字:throws,throw,try,catch,finally分别代表什么意义?在try块中可以抛出异常吗?

JAVA语言如何进行异常处理,关键字throws,throw,try,catch,finally分别代表啥意义在try块中抛出异常吗