异常处理:
try{} catch{} finally{} 语句处理方式:
package edu.xcdq;
public class Demo01 {
public static void main(String[] args) {
int divisor = 10;
int dividend = 0;
// System.out.println(divisor / dividend); // ArithmeicException 算术异常
try {
System.out.println(divisor / dividend); // ArithmeicException 算术异常
}catch (Exception e){
e.printStackTrace();
System.out.println("捕获一个异常");
}finally {
System.out.println("不论如何都会执行这里 ");
}
System.out.println("哈哈哈哈哈哈哈哈哈");
}
}
package edu.xcdq;
import java.util.Scanner;
public class Demo02 {
public static void main(String[] args) {
int [] a =new int[2];
Scanner scanner = new Scanner(System.in);
try {
int i = scanner.nextInt();
int j = scanner.nextInt();
a[0] =i;
a[2] = j;
System.out.println(a[0] /a[2]);
}catch (IndexOutOfBoundsException e){
System.out.println("数组越界异常");
}catch (NumberFormatException e){
System.out.println("数据格式不正常");
}catch (ArithmeticException e){
System.out.println("算术异常");
}
}
}
Demo02的简写方式:
package edu.xcdq;
import java.util.Scanner;
public class Demo03 {
public static void main(String[] args) {
int [] a =new int[2];
Scanner scanner = new Scanner(System.in);
try {
int i = scanner.nextInt();
int j = scanner.nextInt();
a[0] =i;
a[2] = j;
System.out.println(a[0] /a[2]);
}catch (ArithmeticException|NumberFormatException|IndexOutOfBoundsException e){
System.out.println("数组越界异常");
System.out.println("数据格式不正常");
System.out.println("算术异常");
System.out.println("以上异常中的一个");
}
}
package edu.xcdq;
public class Demo04 {
public static void main(String[] args) throws Exception{ //继续向上声明异常,不处理
try {
setSex("变性人");
}catch (Exception e){ //调用者处理异常
e.printStackTrace();
System.out.println("非男非女");
}
setSex("sdsffdf");
}
public static void setSex(String sex) throws Exception{ //声明异常
if( ! (sex.equals("男")||sex.equals("女")) ) {
throw new Exception("处理不了的异常.扔出去"); //抛出异常
}
}
接上:
package edu.xcdq;
public class Demo05 {
public static void main(String[] args) throws Exception { //继续向上声明异常,不处理
try {
setSex("变性人");
}catch (Exception e){ //调用者处理异常
System.out.println("调用者说处理过了");
}
}
public static void setSex(String sex) throws SexException { //声明异常
if (!(sex.equals("男") || sex.equals("女"))) {
throw new SexException("发现一个不对劲的"); //抛出异常
}
}
}
package edu.xcdq;
public class SexException extends Exception {
public SexException(){
}
public SexException(String message){
System.out.println("message");
System.out.println("我是自定义的异常,知道是非男非女,但是我也没法处理");
System.out.println("...");
}