希望编写代码而不会引发异常

时间:2018-07-06 07:58:44

标签: java java-8

我有下面的代码。

import java.io.*;
public class FileTest {
    public static void main(String[] args) throws IOException {
        WriteLinesToFile("miss.txt","This is a special file");
    }

    public static void WriteLinesToFile(String outputFileName, String lineConverted) throws IOException {
        File f = new File(outputFileName);
        if (f.createNewFile()) {
            System.out.println("File is created!");
            FileWriter writer = new FileWriter(f);
            writer.write(lineConverted);
            writer.close();
        } else {
            System.out.println("File already exists.");
            FileWriter writer = new FileWriter(f);
            writer.write(lineConverted);
            writer.close();
        }
    }
}

我需要相同的逻辑,而不会引发异常。有人可以告诉我该怎么做吗?

1 个答案:

答案 0 :(得分:0)

您可以尝试使用try {} catch(IOException e){}

处理异常

但是处理异常很重要,因为否则程序将执行某些操作,而不是您想要的操作。

import java.io.*;
public class FileTest {
public static void main(String[] args)
{
    writeLinesToFile("miss.txt", "This is a special file");
}

public static void writeLinesToFile(String outputFileName, String lineConverted){
    File f = new File(outputFileName);
    try {
        if (f.createNewFile()) {
            System.out.println("File is created!");
            FileWriter writer = new FileWriter(f);
            writer.write(lineConverted);
            writer.close();
        } else {
            System.out.println("File already exists.");
            FileWriter writer = new FileWriter(f);
            writer.write(lineConverted);
            writer.close();
        }
    }
    catch(IOException e){
        //Handle your error
    }
}}

但是您根本无法消除异常,因为在Java中处理文件总是会抛出异常(例如,如果找不到文件)。