Home | 简体中文 | 繁体中文 | 杂文 | Github | 知乎专栏 | Facebook | Linkedin | Youtube | 打赏(Donations) | About
知乎专栏

6.3. SneakyThrows

6.3.1. 处理所有异常 Exception

		
    public static void exceptionTest() {
        File file = new File("/tmp/test.txt");
        try {
            FileReader fileReader = new FileReader(file);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static void exceptionTest() throws Exception {
        File file = new File("/tmp/test.txt");
        FileReader fileReader = new FileReader(file);
    }
		
			

使用 @SneakyThrows 注解,替代写法

		
    @SneakyThrows
    public static void exceptionTest(String pathname) {
        File file = new File(pathname);
        FileReader fileReader = new FileReader(file);
    }		
		
			

6.3.2. 处理特定异常

			
	public static void exceptionTest() {
        File file = new File("/tmp/test.txt");
        try {
            FileReader fileReader = new FileReader(file);
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

    public static void exceptionTest() throws FileNotFoundException {
        File file = new File("/tmp/test.txt");
        FileReader fileReader = new FileReader(file);
    }
			
			

使用 @SneakyThrows 注解,替代写法

			
    @SneakyThrows(FileNotFoundException.class)
    public static void exceptionTest(File file) {
        FileReader fileReader = new FileReader(file);
    }
			
			

6.3.3. 抛出异常

			
package cn.netkiller.test;

import lombok.SneakyThrows;

public class Test {
    @SneakyThrows
    public static void throwExceptionTest(String message) {
        throw new IllegalStateException(message);
    }


    public static void main(String[] args) {
        try {
            throwExceptionTest("Test");
        } catch (Exception e) {
            System.out.println(e);
        }

    }
}