运行时异常:
1、空指针异常
package 异常处理;
import org.junit.Test;
public class ExceptionTest {
//NullPointerException空指针异常
@Test
public void test1(){
int[] arr=null;
System.out.println(arr[3]);
}
}
package 异常处理;
import org.junit.Test;
public class ExceptionTest {
//NullPointerException空指针异常
@Test
public void test1(){
// int[] arr=null;
// System.out.println(arr[3]);
String str=null;
System.out.println(str.charAt(0));
//charAt():输出第X个字符
}
}
2、数组角标越界
package 异常处理;
import org.junit.Test;
public class ExceptionTest {
//NullPointerException空指针异常
@Test
public void test2() {
// int[] arr=null;
// System.out.println(arr[3]);
// String str=null;
// System.out.println(str.charAt(0));
int[] arr = new int[10];
System.out.println(arr[10]);
}
}
3、两个类型间转换不兼容:ClassCastException
package 异常处理;
import java.util.Date;
import org.junit.Test;
public class ExceptionTest {
// ClassCastException
@Test
public void test3() {
Object obj = new Date();
String str1 = (String) obj;
}
}
4、NumberFormatException
package 异常处理;
import java.util.Date;
import org.junit.Test;
public class ExceptionTest {
// NumberFormatException
@Test
public void test4() {
String str1 = "123";
str1 = "abc";
int num = Integer.parseInt(str1);
}
}
5、InputMismatchException
package 异常处理;
import java.util.Scanner;
import org.junit.Test;
public class ExceptionTest {
// NumberFormatException
@Test
public void test5() {
Scanner scanner = new Scanner(System.in);
int score = scanner.nextInt();
System.out.println(score);
}
}
6、ArithmeticException:算术异常
package 异常处理;
import java.util.Scanner;
import org.junit.Test;
public class ExceptionTest {
// ArithmeticException
@Test
public void test5() {
int a = 10;
int b = 0;
System.out.println(a / b);
}
}
二、编译时异常
略....