需要導入一個mysql的驅動
Runtime Exception
運行時異常
- 類型轉換異常
- 空指針異常
- 文件找不到異常
- 類找不到異常
- 數組大小爲負數異常
- 數組越界異常
- 同步修改異常
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
class Animal {
}
/**
* 運行時異常: 類型轉換異常 空指針異常 文件找不到異常 類找不到異常 數組大小爲負數異常 數組越界異常 同步修改異常
*
* @author 邢質坦 2019年2月6日 下午8:21:02
*/
public class TestDemo {
public static void main(String[] args) {
// 類型轉換異常——java.lang.ClassCastException
Object o = new TestDemo();
Animal animal = (Animal) o;
// 空指針異常——java.lang.NullPointerException
Set<Integer> hashSet = new HashSet<Integer>();
hashSet.add(null); // will throw null pointer
// hashSet.remove(null);
Iterator<Integer> it = hashSet.iterator();
/*
* while (it.hasNext()) {
*
* int i = it.next();
*
* }
*/
FileInputStream fileInputStream = null;
// 文件找不到異常——java.io.FileNotFoundException
/*
* File file = new File("xx.xx"); try { fileInputStream = new
* FileInputStream(file); } catch (FileNotFoundException e1) { // TODO
* Auto-generated catch block e1.printStackTrace(); }finally{
* if(null!=fileInputStream){ try { fileInputStream.close(); } catch
* (IOException e) { // TODO Auto-generated catch block
* e.printStackTrace(); } } }
*/
// 數組越界異常——java.lang.ArrayIndexOutOfBoundsException
int[] arr = { 1, 2, 3, 4, 5 };
// int j = arr[5];
// 類找不到異常
try {
// java.lang.ClassNotFoundException
// Class.forName("com");
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 數組大小爲負數異常
// java.lang.NegativeArraySizeException
// int[] a = new int[-1];
// 同步修改異常——java.util.ConcurrentModificationException
ArrayList<Integer> arrayList = new ArrayList<Integer>();
for (int i = 0; i < 10; i++) {
arrayList.add(i);
}
for (int x : arrayList) {
System.out.println(x);
// arrayList.remove(x);//java.util.ConcurrentModificationException
}
}
}