错误(程序员不可控制):StackOverflowError:
package com.anonymous.javase.day05;
public class Demo1 {
public static void main(String[] args) {
Demo1.main(args);
/*Exception in thread "main" java.lang.StackOverflowError*/
//递归异常
}
}
常见的几种异常:
NullPointException/ArraysindexOutOfBoundException/NumberFormatException等等....
package com.anonymous.javase.day05;
public class Demo2 {
public static void main(String[] args) {
//NullPointException空指针异常
NullPointExceptionTest();
//ArraysindexOutOfBoundException数组索引越界
ArraysindexOutOfBoundExceptionTest();
//NumberFormatExceptionTest()数字格式化异常
NumberFormatExceptionTest();
}
public static void NullPointExceptionTest(){
String[] str = null;
System.out.println(str.length);
/*Exception in thread "main" java.lang.NullPointerException*/
}
public static void ArraysindexOutOfBoundExceptionTest(){
String[] str = {"3","4"};
System.out.println(str[3]);
/*Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3*/
}
public static void NumberFormatExceptionTest(){
Integer valueOf = Integer.valueOf("345lsfds");
System.out.println(valueOf);
/*Exception in thread "main" java.lang.NumberFormatException: For input string: "345lsfds"*/
}
}
try.....catch(捕获异常.处理异常)
public static void NullPointerExceptionTest(){
String[] str = null;
try{
System.out.println(str.length);
}catch(NullPointerException e){
//获取异常信息
System.out.println(e.getMessage());
//获取异常信息类型
System.out.println(e.toString());
//获取异常信息.并跟踪异常信息位置
e.printStackTrace();
}
/*Exception in thread "main" java.lang.NullPointerException*/
}
捕获多层异常:
package com.anonymous.javase.day05;
public class Demo3 {
//捕获多层异常
/**
* 有时候不知道会出现什么样的异常,可以将异常归于Exception统一处理异常信息
*/
public static void main(String[] args) {
try{
int sum = Integer.parseInt(null);
double d = 10 / sum;
System.out.println(d);
}catch(NumberFormatException e){
System.out.println(e.getMessage());
}catch(ArithmeticException e){
System.out.println(e.getMessage());
}catch(Exception e){
System.out.println("网络异常!");
}
}
}
package com.anonymous.javase.day05;
public class Demo4 {
//使用finally
public static void main(String[] args) {
try {
System.out.println(100/10);
} catch (Exception e) {
e.printStackTrace();
}finally{
System.out.println("执行该程序!");
}
/*java.lang.ArithmeticException: / by zero
at com.anonymous.javase.day05.Demo4.main(Demo4.java:7)
执行该程序!(无论什么情况下,改程序都会执行)
*/
//面试题
int test1 = test1();
int test2 = test2();
System.out.println(test2);
System.out.println(test1);
}
private static int test2() {
try{
return 10;
}finally{
return 100;
}
}
private static int test1() {
int a = 1;
try{
return
a;
}finally{
return ++a;
//和a++和++a道理差不多
}
}
}