32.Java基础_异常
2024-09-01 22:25:15
JVM虚拟机默认异常处理机制
Java异常处理:
1.try...catch...
2.throw
1.try...catch...
public class test{
public static void main(String[] args) {
System.out.println("开始");
method();
System.out.println("结束");
}
public static void method(){
int[] arr={1,2,3};
try {
System.out.println(arr[3]); //访问超出索引
}
catch (ArrayIndexOutOfBoundsException e){
e.printStackTrace();
}
}
}
/*
开始
java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
at pack2.test.method(test.java:13)
at pack2.test.main(test.java:7)
结束
*/
Exception异常类常用方法
编译时异常和运行时异常
2.throws
throws将异常抛出去,让try_catch_来处理
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class test{
public static void main(String[] args) {
System.out.println("开始");
try {
method();
}
catch (ArrayIndexOutOfBoundsException e){
e.printStackTrace();
}
try {
method2();
}
catch (ParseException e){
e.printStackTrace();
}
System.out.println("结束");
}
//编译时异常,不加throws ParseException不能编译
public static void method2() throws ParseException {
String s="2048-08-09";
SimpleDateFormat sdf=new SimpleDateFormat("yyy-MM-dd");
Date d=sdf.parse(s);
System.out.println(d);
}
//运行时异常,不加throws ArrayIndexOutOfBoundsException可以编译
public static void method() throws ArrayIndexOutOfBoundsException{
int[] arr={1,2,3};
System.out.println(arr[3]);
}
}
/*
开始
java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
at pack2.test.method(test.java:36)
at pack2.test.main(test.java:13)
Sun Aug 09 00:00:00 CST 2048
结束
*/
自定义异常
public class ScoreException extends Exception{
public ScoreException() {}
public ScoreException(String message) {
super(message);
}
} public class Teacher{
public void checkScore(int score) throws ScoreException{
if(score<0||score>100){
throw new ScoreException(); //抛出异常对象
}
else {
System.out.println("分数正常");
}
}
} import java.util.Scanner;
public class test{
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("请输入分数:");
int score=sc.nextInt();
Teacher t=new Teacher();
try {
t.checkScore(score);
}
catch (ScoreException e){
e.printStackTrace();
}
}
}
最新文章
- Windows10自适应和交互式toast通知[1]
- Android自定义控件1
- Codeforces 724C [坐标][乱搞][模拟]
- 《极客学院 --NSAttributedString 使用详解-4-UITextKit 简介》学习笔记(待处理)
- Android判断网络状态
- 003-python基础-变量与常量
- ubuntu下使用quick2wire控制RespberryPi2的I2C
- Photoshop快捷键
- Paxos算法深入分析
- jmeter简单的接口性能测试
- 把玩Alpine linux(二):APK包管理器
- 【Android开发坑系列】之窗口管理
- 在python程序中的进程操作
- spring-boot-2.0.3启动源码篇 - 阶段总结
- 个人作业Week1
- python2中在sqlite3中插入中文
- Chapter 2 Open Book——26
- 解题:HNOI 2014 世界树
- Python MQTT订阅获取发布信息字典过滤
- HTML5触摸事件演化tap事件
热门文章
- HDU1561 The more ,The better (树形背包Dp)
- Python3 函数基础2
- Java并发编程杂记(1)
- [Python]实现字符串倒序的三种方法
- 关于eclipse码代码时光标自动消失要重新点击输入框的问题
- 建议2:注意Javascript数据类型的特殊性---(4)避免误用parseInt
- java基础面向对象总结(一)
- 如何入侵SF服务器/充当GM刷元宝
- 如何快速将多个excel表格的所有sheet合并到一个sheet中
- MESSAGE_TYPE_X dump in RSM_DATASTATE_CHECK -6-