java异常类的使用
2024-10-18 19:24:28
1.异常的概念
什么是异常?程序出错分为两部分,编译时出粗和运行时出错。编译时出错是编译器在编译源码时发生的错误;
运行时出错是在编译通过,在运行时出现的错误。这种情况叫异常。
例如:数组越界,除数为0,文件找不到等等。
异常的层次:
Object
Throwable
Error
Exception
RuntimeException
IOException
2.如何解决异常
a.使用try...catch
public class UsingTryCatch {
public static void main(String args[]) {
int a = 5;
int b = 0;
int result = 0;
try {
result = a / b;
} catch (Exception e) {
System.out.println(e);
}
} }
b.使用throws或throw关键字
public class UsingThrows {
public static void main(String args[]) {
try {
Caculation caculation = new Caculation();
} catch (Exception e) {
e.printStackTrace();
}
} public static class Caculation{
int a = 5;
int b = 0;
int result = 0; public Caculation()throws Exception{
result = a/b;
System.out.println(result);
}
}
}
public class UsingThrow {public static void main(String args[]) {
try {
// Caculation caculation = new Caculation();
throw new Exception("实例化Exception");
} catch (Exception e) {
e.printStackTrace();
}
} public static class Caculation{
int a = 5;
int b = 0;
int result = 0; public Caculation()throws Exception{
result = a/b;
System.out.println(result);
}
}
}
最新文章
- xpath使用
- 解决在使用client object model的时候报“object does not belong to a list”错误
- django入门记录 2
- Kinect SDK 安装失败
- Hibernate简单分页
- Spring MVC中使用 Swagger2 构建Restful API
- (转)Sql Server 对锁的初步认识
- Android中利用画图类和线程画出闪烁的心形
- oracle 主键应用序列和触发器实现自动增长
- MFC实现多风格真彩色大图标工具栏按钮
- count 数字计数(bzoj 1833)
- php 个推的例子
- POI导出EXCEL,浏览器不兼容,文件名称乱码,文件无法打开解决方法
- pytest进阶之conftest.py
- DSAPI WIN7磨砂+窗体投影组合
- Python中xlrd模块解析
- 用python探索和分析网络数据
- word空白页怎么删除
- 2018.06.27"Shortest" pair of paths(费用流)
- thinkphp5学习总结!
热门文章
- 在Eclipse中安装spket插件
- SQL server 变量if,while,存储过程
- 数学(概率)CodeForces 626D:Jerry's Protest
- java 学习连接
- Delphi中TxmlDocument控件的用法 转
- Linq to SQL 类型的对象图包含循环,如果禁用引用跟踪,择无法对其进行序列化。
- HDOJ 2018 母牛的故事
- Hdu 3966-Aragorn's Story LCT,动态树
- 《University Calculus》-chaper13-多重积分-二重积分的计算
- HBase 简介(强烈推荐看)