Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/oracle/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Java中使用自定义异常_Java_Bluej - Fatal编程技术网

在Java中使用自定义异常

在Java中使用自定义异常,java,bluej,Java,Bluej,我试图用java抛出我的自定义异常,但目前我没有运气。我有两个类:readWrite类,它允许用户输入文件名和要写入文件的文本(通过构造函数)。它有三个方法,write、read和writeToFile,用于验证文件是否以.txt结尾。如果它现在以.txt结尾,则应抛出我的自定义异常类,声明“抱歉,但此系统仅接受.txt文件”,这是我在自定义异常中的toString()方法中创建的。我似乎无法使它工作,下面是代码,有些可能会有帮助,我希望我已经解释清楚,因为我是Java新手,注意我已经注释了一些

我试图用java抛出我的自定义异常,但目前我没有运气。我有两个类:readWrite类,它允许用户输入文件名和要写入文件的文本(通过构造函数)。它有三个方法,write、read和writeToFile,用于验证文件是否以.txt结尾。如果它现在以.txt结尾,则应抛出我的自定义异常类,声明“抱歉,但此系统仅接受.txt文件”,这是我在自定义异常中的toString()方法中创建的。我似乎无法使它工作,下面是代码,有些可能会有帮助,我希望我已经解释清楚,因为我是Java新手,注意我已经注释了一些代码,因为我正在尝试一些不同的东西使它工作

ReadWrite.java

import java.io.*;

public class ReadWrite
{   
    private final String file;
    private final String text;

    public ReadWrite(String file, String text)
    {
        // initialise instance variables
        this.file=file;
        this.text=text;   
    }

    private void write() //throws InvalidFileException 
    {
        try {
            FileWriter writer = new FileWriter(file);

            writer.write(text);
            writer.write('\n');
            writer.close();
        }
        catch(IOException e)
        {
            System.out.print(e);
        }
    }

    public boolean writeToFile() 
    {    
        boolean ok;

        try{        
            FileWriter writer = new FileWriter(file);       
            {   
                if(file.toLowerCase().endsWith(".txt"))
                {  
                    write();
                    ok = true;
                } //if end
                else{
                    ok=false;
                    //throw new InvalidFileException();
               } //else end
            }
        } //try end
        catch(IOException e) {
           ok=false; 
        } // catch end         
        //catch (InvalidFileException e){

            //System.out.println(e.toString());
        //}
        return ok;
    }

    public void read(String fileToRead)
    {
        try {
            BufferedReader reader = new BufferedReader(new FileReader(fileToRead));
            String line = reader.readLine();

            while(line != null) {
               System.out.println(line);
               line = reader.readLine();
            }// while end

            reader.close();

        }//try end
        catch(FileNotFoundException e) {                  
            System.out.println(fileToRead + " the system can not     find the file specified");                  
        }  //catch end
        catch(IOException e) {                          
            e.printStackTrace();

        } //catch end
    }
}
import java.io.FileNotFoundException;
import java.io.*;

public class InvalidFileException extends Exception
{
    /**
     * Constructor for objects of class InvalidFileException
     */
    public InvalidFileException(String message)
    {
        super(message);
    }

    public String toString()
    {
        return ("Sorry but this system only accepts .txt files");
    }
}
InvalidFileException.java

import java.io.*;

public class ReadWrite
{   
    private final String file;
    private final String text;

    public ReadWrite(String file, String text)
    {
        // initialise instance variables
        this.file=file;
        this.text=text;   
    }

    private void write() //throws InvalidFileException 
    {
        try {
            FileWriter writer = new FileWriter(file);

            writer.write(text);
            writer.write('\n');
            writer.close();
        }
        catch(IOException e)
        {
            System.out.print(e);
        }
    }

    public boolean writeToFile() 
    {    
        boolean ok;

        try{        
            FileWriter writer = new FileWriter(file);       
            {   
                if(file.toLowerCase().endsWith(".txt"))
                {  
                    write();
                    ok = true;
                } //if end
                else{
                    ok=false;
                    //throw new InvalidFileException();
               } //else end
            }
        } //try end
        catch(IOException e) {
           ok=false; 
        } // catch end         
        //catch (InvalidFileException e){

            //System.out.println(e.toString());
        //}
        return ok;
    }

    public void read(String fileToRead)
    {
        try {
            BufferedReader reader = new BufferedReader(new FileReader(fileToRead));
            String line = reader.readLine();

            while(line != null) {
               System.out.println(line);
               line = reader.readLine();
            }// while end

            reader.close();

        }//try end
        catch(FileNotFoundException e) {                  
            System.out.println(fileToRead + " the system can not     find the file specified");                  
        }  //catch end
        catch(IOException e) {                          
            e.printStackTrace();

        } //catch end
    }
}
import java.io.FileNotFoundException;
import java.io.*;

public class InvalidFileException extends Exception
{
    /**
     * Constructor for objects of class InvalidFileException
     */
    public InvalidFileException(String message)
    {
        super(message);
    }

    public String toString()
    {
        return ("Sorry but this system only accepts .txt files");
    }
}
试试这个:

private void write() throws InvalidFileException {
try {
    if(!file.getName().endsWith(".txt") {
        throw new InvalidFileException(".txt files only.");
    }
    FileWriter writer = new FileWriter(file);

    writer.write(text);
    writer.write('\n');
    writer.close();
}
catch(IOException e)
{
    // handle exception please.
}
请注意,为了打印自定义消息,您必须重写异常的“getMessage()”方法。或者在super()调用中设置它


重写toString()方法会使您的super()调用以及传递给异常的自定义(详细信息)消息(在我的示例中为“.txt files only.”)过时,因为此字符串将不再打印。

以下是您的要求:

它不应该抛出我的自定义异常类,声明 “抱歉,此系统只接受.txt文件”

我想你是因为
toString
而感到困惑的。你真的不需要那种
toString
方法。您正确地实现了一个
InvalidFileException
,它接受一个
字符串
参数

所以,现在您只需要
抛出新的InvalidFileException(“对不起,这个系统只接受.txt文件”)或在抛出
InvalidFileException
时使用所需的任何字符串消息

请注意,如果您从一个方法中抛出异常,并在同一个方法中捕获它,则看起来不合逻辑,除非您这样做是因为APM(应用程序性能监视)工具用于日志记录

另一方面,如果您像这样抛出异常,那么您需要在方法签名中添加一个
throw
语句,指示此方法“可能”抛出某某异常。因此,该方法的调用可以重新抛出或捕获它


如果您正在某个地方捕获异常,那么在异常对象上使用
getMessage
方法,您将得到与抛出异常时放置的相同的消息,在这种情况下-“抱歉,但此系统只接受.txt文件”
InvalidFileException
扩展了
Exception
,但您只能尝试捕获
IOException
FileNotFoundException
。我认为您的意思是让
InvalidFileException
extend
IOException

您不显示您在
ReadWrite
中使用任何方法的代码,并且您将抛出自定义异常的行被注释掉。请发布您的问题的详细信息。您是如何实现的?抛出
InvalidFileException
的方法在哪里?您在代码中从哪里捕获它?猜测一下:如果您创建一个或多个带参数的显式构造函数,Java不会生成默认的无参数构造函数。e.toString()不会打印任何内容。使用e.printStackTrace()或e。getMessage()永远不要将catch块保留为空。你只是在问问题,基本上你是对的。此代码几乎是演示给定问题解决方案的示例。;)