「Java」例外RuntimeExceptionを使うサンプル

2020年10月15日

説明
public RuntimeException(Throwable cause)
指定された原因と詳細メッセージ(cause==null ? null : cause.toString())を持つ新しい実行時例外を構築します
(通常、causeのクラスと詳細メッセージを含みます)。このコンストラクタは、実行時例外がほかのスロー可能オブジェクトのラッパーである場合に有用です。
Javaコード

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
package com.arkgame.study;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
public class RuntimeExceptionDemo {
public static void main(String[] args) throws UnsupportedEncodingException {
try {
FileInputStream fin = new FileInputStream("c:\\date\\test.csv");
InputStreamReader ist = new InputStreamReader(fin, "UTF-8");
BufferedReader reader = new BufferedReader(ist);
//some code
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
}
}
}
package com.arkgame.study; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; public class RuntimeExceptionDemo { public static void main(String[] args) throws UnsupportedEncodingException { try { FileInputStream fin = new FileInputStream("c:\\date\\test.csv"); InputStreamReader ist = new InputStreamReader(fin, "UTF-8"); BufferedReader reader = new BufferedReader(ist); //some code } catch (FileNotFoundException e) { throw new RuntimeException(e); } } }
package com.arkgame.study;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

public class RuntimeExceptionDemo {

      public static void main(String[] args) throws UnsupportedEncodingException {
            try {
                  FileInputStream fin = new FileInputStream("c:\\date\\test.csv");
                  InputStreamReader ist = new InputStreamReader(fin, "UTF-8");
                  BufferedReader reader = new BufferedReader(ist);
                  //some code
            } catch (FileNotFoundException e) {
                  throw new RuntimeException(e);
            }

      }

}

結果
Exception in thread “main" java.lang.RuntimeException: java.io.FileNotFoundException: c:\date\test.csv (指定されたパスが見つかりません。)
at com.arkgame.study.RuntimeExceptionDemo.main(RuntimeExceptionDemo.java:17)
Caused by: java.io.FileNotFoundException: c:\date\test.csv (指定されたパスが見つかりません。)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(FileInputStream.java:195)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at java.io.FileInputStream.<init>(FileInputStream.java:93)
at com.arkgame.study.RuntimeExceptionDemo.main(RuntimeExceptionDemo.java:13)

Java

Posted by arkgame