异常概述:
try{ } catch{ }:
package daysreplace;import com.sun.jdi.IntegerValue;import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.Scanner;public class Test {public static void main(String[] args) throws ParseException {System.out.println("开始");try {a1();}catch (Exception e){System.out.println("您访问的下标越界了!");e.printStackTrace();//打印异常的结果}System.out.println("结束");}public static void a1(){int[] arr={22,323,22};System.out.println(arr[3]);}
}
Throwable的成员方法:
package daysreplace;import com.sun.jdi.IntegerValue;import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.Scanner;public class Test {public static void main(String[] args) throws ParseException {try{System.out.println("开始");a1();}catch (Exception e){e.printStackTrace();System.out.println("异常内容:"+e.getMessage());//e.getSystem.out.println("异常内容:"+e.toString());System.out.println("转换类型错误啦!");}System.out.println("结束");}public static void a1(){String str="1,2,34,4";int i = Integer.parseInt(str);System.out.println(i);// int[] arr={22,323,22};
// System.out.println(arr[3]);}}
编译时异常和运行时异常的区别:
throws 关键字:
自定义异常,继承Exception即可:
LoginException.java:
package dateStudy;public class LoginException extends Exception{//alt+insert 生成一个有参构造public LoginException(String message) {super(message);}}
LoginTest.java:
package dateStudy;import java.util.Locale;
import java.util.Scanner;public class LoginTest {public static void main(String[] args) throws LoginException {System.out.println("开始");System.out.println("请输入账号");Scanner sc = new Scanner(System.in);String s = sc.nextLine();System.out.println("请输入密码");Scanner sc1 = new Scanner(System.in);String s1 = sc1.nextLine();try {login(s,s1);} catch (LoginException e) {e.printStackTrace();}System.out.println("结束");}public static void login(String userName, String pwd) throws LoginException {if (!("wwx".equals(userName)&&"123456".equals(pwd))) {throw new LoginException("用户输入的账号和密码不正确");}System.out.println("输入正确,登陆成功");}}