[Java]throw例外(Exception)処理をスローするサンプル
書式
throw new Exception(xxx)
使用例
package com.arkgame.study.map;
import java.util.HashMap;
import java.util.Map;
public class ExceptionDemo {
//HashMapの定義
protected static Map<String, Integer> mp = new HashMap<String, Integer>();
protected static final String pkey = "k03";
public static void main(String[] args) throws Exception {
// HashMapに要素を挿入
mp.put("k01", 21);
// 関数showを呼び出す
show(mp);
}
// 引数:Map<String, Integer>
public static void show(Map<String, Integer> mp) throws Exception {
// キー存在チェック
if (mp.containsKey(pkey)) {
System.out.println("キー存在");
} else {
throw new Exception(String.format("キーが存在しません"));
}
}
}
package com.arkgame.study.map;
import java.util.HashMap;
import java.util.Map;
public class ExceptionDemo {
//HashMapの定義
protected static Map<String, Integer> mp = new HashMap<String, Integer>();
protected static final String pkey = "k03";
public static void main(String[] args) throws Exception {
// HashMapに要素を挿入
mp.put("k01", 21);
// 関数showを呼び出す
show(mp);
}
// 引数:Map<String, Integer>
public static void show(Map<String, Integer> mp) throws Exception {
// キー存在チェック
if (mp.containsKey(pkey)) {
System.out.println("キー存在");
} else {
throw new Exception(String.format("キーが存在しません"));
}
}
}
package com.arkgame.study.map; import java.util.HashMap; import java.util.Map; public class ExceptionDemo { //HashMapの定義 protected static Map<String, Integer> mp = new HashMap<String, Integer>(); protected static final String pkey = "k03"; public static void main(String[] args) throws Exception { // HashMapに要素を挿入 mp.put("k01", 21); // 関数showを呼び出す show(mp); } // 引数:Map<String, Integer> public static void show(Map<String, Integer> mp) throws Exception { // キー存在チェック if (mp.containsKey(pkey)) { System.out.println("キー存在"); } else { throw new Exception(String.format("キーが存在しません")); } } }
結果
Exception in thread “main" java.lang.Exception: キーが存在しません
at Sample/com.arkgame.study.map.ExceptionDemo.show(ExceptionDemo.java:24)
at Sample/com.arkgame.study.map.ExceptionDemo.main(ExceptionDemo.java:16)