Try and catch blocks: whether in the class itself or when I call the method outside the class

Trts

Could you help me understand where should I throw exceptions and catch them. Please, have a look at my code. I thought that in Thrd class I have already thrown and caught the exception. But when I wrote in the main class FirstThread.readFile("ParallelProgramming.txt");, I faced a runtime error - unhandled exception. So, I had to use try and catch. So, I somehow can't understand why in the Thd class my try and catch blocks didn't work.

package parallelprogramming;

import java.lang.Thread;
import java.io.*;

public class Thrd extends Thread {

    public void readFile(String File) throws FileNotFoundException {
        FileReader fr = new FileReader(File);
        BufferedReader br = new BufferedReader(fr);
        String s;
        try {
            while ((s = br.readLine()) != null) {
                System.out.println(s);
            }
            fr.close();
        } 
        catch (FileNotFoundException FNFD) {
            System.out.println("File not found!");
        }
        catch (IOException IOE){
            System.out.println("IOException caught!");
        }        
    }
}

package parallelprogramming;

import java.io.FileNotFoundException;

public class ParallelProgramming {

    public static void main(String[] args) throws FileNotFoundException {
        Thrd FirstThread = new Thrd();
        try {
            FirstThread.readFile("ParallelProgramming.txt");
        } catch (FileNotFoundException FNFD) {
            System.out.println("File not found!");
        }
    }
}
fge

The rules with checked exceptions (and this includes IOException, which FileNotFoundException is a child of), are as follows:

  • if you cannot, or do not want, to handle it in your current method, declare that the method throws it;
  • if you want to handle it in your current method, then catch it; note that even in this case you can rethrow that exception;
  • if main() throws any exception, and this exception triggers, the program terminates.

Now, we suppose that you are using Java 7. In this case, do that:

public void readFile(final String file)
    throws IOException
{
    final Path path = Paths.get(file);
    for (final String line: Files.readAllLines(path, StandardCharsets.UTF_8))
        System.out.println(line);
}

Why bother? ;)

If you don't want to do that but read line by line, then:

public void readFile(final String file)
    throws IOException
{
    final Path path = Paths.get(file);
    try (
        final BufferedReader reader = Files.newBufferedReader(path,
            StandardCharsets.UTF_8);
    ) {
        String line;
        while ((line = reader.readLine()) != null)
            System.out.println(line);
    }
}

The second form is preferred if you wish to treat exceptions specifically. Note that with Java 7, you have meaningful exceptions as to why you cannot access the file vs IOException: NoSuchFileException, AccessDeniedException, etc etc. All these inherit FileSystemException. The old file API can't do that for you.

This means that if you want to deal with filesystem level errors you can do:

catch (FileSystemException e) { /* ... */ }

where before that you did:

catch (FileNotFoundException e) { /* ... */ }

Translated to the code above, if you want to catch exceptions you'll then do:

// All exceptions handled within the method -- except if you rethrow it
public void readFile(final String file)
{
    final Path path = Paths.get(file);
    try (
        final BufferedReader reader = Files.newBufferedReader(path,
            StandardCharsets.UTF_8);
    ) {
        String line;
        while ((line = reader.readLine()) != null)
            System.out.println(line);
    } catch (FileSystemException e) {
        // deal with a filesystem-level error
        // Note that you MUSt catch it before IOException
        // since FileSystemException inherits IOException
    } catch (IOException e) {
        // deal with a low-level I/O error
    }
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

Call derived class method from base class instance

来自分类Dev

Call method in different class from click event method in c#

来自分类Dev

Where should I implement my class method?

来自分类Dev

C# Inheritance Prevent Base Class Method Call Derived Class method

来自分类Dev

Swift: How to call a category or class method from Objective-C

来自分类Dev

method()与Class.method()?

来自分类Dev

Variable assignment outside class definition

来自分类Dev

How to call a js function when an element with a particular class is hovered?

来自分类Dev

How to control on div class blocks using the keyboard

来自分类Dev

Correctly init NSCoder in sub class when init NSCoder is convenience method in base class in Swift

来自分类Dev

反映class <T> .method

来自分类Dev

Create a method attribute in a class

来自分类Dev

System cannot find the file specified when I try to call an executable file in C#

来自分类Dev

从* class *构造函数发出的catch事件

来自分类Dev

Accessing outer class members from within an inner class extending the outer class itself

来自分类Dev

UITableView is being reset when I use Custom Class

来自分类Dev

Call a function from an another class

来自分类Dev

Condense successive 'try' blocks

来自分类Dev

Objective-C Class Method

来自分类Dev

Passing @Context argument to method in class

来自分类Dev

javascript class.method1.method2

来自分类Dev

如何使用嵌套在 try { } catch { } 中的 Jest on call 编写测试

来自分类Dev

try catch语句的位置

来自分类Dev

从try {} catch {}访问变量

来自分类Dev

声明try catch块

来自分类Dev

遍历try / catch块?

来自分类Dev

php - try, catch, and retry

来自分类Dev

Java Try Catch块

来自分类Dev

PHP包括try catch

Related 相关文章

热门标签

归档