Main
···
package edu.xcdq;
public class Main {
public static void main(String[] args) {
int divisor = 10 ;
int dividend = 0 ;
try{
System.out.println(divisor / dividend);//ArithmeticException 算數(shù)異常
}catch (Exception e){
e.printStackTrace();
System.out.println("捕獲到一個(gè)異常");
}finally {
System.out.println("不管怎都會(huì)執(zhí)行這個(gè)代碼");
}
System.out.println("哈哈");
}
}
···
Demo01
package edu.xcdq;
import java.util.InputMismatchException;
import java.util.Scanner;
/**
* @qvthor liuwenzheng
* @date 2021/4/27 15:07
*/
public class Demo01 {
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 (ArrayIndexOutOfBoundsException e){
System.out.println("數(shù)組越界異常");
}catch (InputMismatchException e){
System.out.println("數(shù)據(jù)格式不正確異常");
}catch (ArithmeticException e){
System.out.println("算數(shù)異常");
}
}
}
Demo02
package edu.xcdq;
import java.util.InputMismatchException;
import java.util.Scanner;
/**
* @qvthor liuwenzheng
* @date 2021/4/27 15:15
*/
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]);
// Array Index OutOf Bounds Exception 數(shù)組享怀、索引 超出 邊界 異常
// Input Mismatch Exception 輸入 不匹配 異常
// Arithmetic Exception 數(shù)字?jǐn)?shù)字 異常
}catch (ArrayIndexOutOfBoundsException |InputMismatchException |ArithmeticException e){
System.out.println("數(shù)組越界異常");
System.out.println("數(shù)據(jù)格式不正確異常");
System.out.println("算數(shù)異常");
}
}
}
Demo03
package edu.xcdq;
/**
* @qvthor liuwenzheng
* @date 2021/4/27 15:31
*/
public class Demo03 {
public static void main(String[] args) throws Exception{ //繼續(xù)向上聲明羽峰,不處理
/*try {
steSex("雙性人");
}catch (Exception e){
e.printStackTrace();
System.out.println("非男非女");
}*/
steSex("afwarf");
}
public static void steSex(String sex) throws Exception{ //聲明異常
if (!(sex.equals("男")|| sex.equals("女"))){
throw new Exception("處理不了的異常,扔出去"); //拋出異常
}
}
}
Demo04
package edu.xcdq;
/**
* @qvthor liuwenzheng
* @date 2021/4/27 15:46
*/
public class Demo04 {
public static void main(String[] args){
try {
steSex("雙性人");
}catch (Exception e){
System.out.println("調(diào)用者說(shuō)處理過(guò)了");
}
}
public static void steSex(String sex) throws SexException{ //聲明異常
if (!(sex.equals("男")|| sex.equals("女"))){
throw new SexException("發(fā)現(xiàn)一個(gè)不對(duì)勁的"); //拋出異常
}
}
}
SexException
package edu.xcdq;
/**
* @qvthor liuwenzheng
* @date 2021/4/27 15:44
*/
public class SexException extends Exception {
public SexException(){
}
public SexException(String message){
System.out.println(message);
System.out.println("自定義的異常添瓷,知道非男飛女梅屉,但是沒(méi)辦法處理");
System.out.println("..........");
}
}