package com.cn2;
public class Demo {
public static void main(String[] args) {
System.out.println("---");
methhod();
System.out.println("------");
}
public static void methhod(){
try {
int[] arr = {1,2,3};
System.out.println(arr[3]);
}catch (ArrayIndexOutOfBoundsException a){
System.out.println("ArrayIndexOutOfBoundsException");
}
}
}
package com.cn2;
public class Demo {
public static void main(String[] args) {
System.out.println("---");
methhod();
System.out.println("------");
}
public static void methhod(){
try {
int[] arr = {1,2,3};
System.out.println(arr[3]);
}catch (ArrayIndexOutOfBoundsException e){//new ArrayIndexOutOfBoundsException;
// System.out.println("ArrayIndexOutOfBoundsException");
e.printStackTrace();//这个最全一般用这个~啥都输出了
// System.out.println(e.getMessage());//Index 3 out of bounds for length 3
// System.out.println(e.toString());
//java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
}
}
}
package com.cn2;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Demo1 {
public static void main(String[] args) {
System.out.println("------");
// method();//运行时异常
method2();
System.out.println("---");
}
public static void method2() {
try {
String s = "2048-11-10";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date d = sdf.parse(s);//编译异常需要用try catch处理
//只是说可能有异常 不是一定有异常 就用parse方法就是告诉大家可能我有问题哦 需要处理如果不用处理那就没问题~
System.out.println(d);
} catch (ParseException e) {
e.printStackTrace();
}
}
public static void method() {
int arr[] = {1, 2, 3};
System.out.println(arr[3]);//ArrayIndexOutOfBoundsException
}
}
情况:有时候会遇到比如考试成绩在一定的范围内 我们就需要用这样异常来处理~
package com.cn3;
import java.util.Scanner;
public class ScoreDemo {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Score:");
int i = sc.nextInt();
Score s = new Score();
try {
s.check(i);//check方法是在Score里面的呀~ 这里会报错的话就写个try就好了
} catch (Exception e) {
e.printStackTrace();
}
}
}
package com.cn3;
public class Score {
public void check(int score) throws Exception{
if(score<0||score>100){
throw new ScoreEception("erro about the score");
//这里写的是抛出异常时自己可以自定义的字符串~~
}else{
System.out.println("right");
}
}
}
package com.cn3;
public class ScoreEception extends Exception {
public ScoreEception(){}
public ScoreEception(String message){
super(message);//可以看到父类往前还有到最后到了Throwable
//所以可以用到里面的fillnStackTrace方法 getMessage方法用到
}
}