黑马程序员----异常处理机制的概括
2015-08-18 21:12
656 查看
第一部分: 异常的认识
异常体系Throwable:
(1)Error:通常出现重大问题如:运行的类不存在或者内存溢出
不编写针对代码对其处理
(2)Exception
在运行时候出现的错误、
Exception都是以父类名作为后缀的
可编写针对性代码对其进行处理
第二部分:异常的处理
Java提供了特有的语句进行处理:
try
{
需要被检测的代码块
}
catch(异常类 变量)
{
处理方式
}
finally
{
}
第三部分:代码举例
(1)通过try-catch方式处理的代码举例
class Demo{
int div(int
a,int b)
{
return(a/b);
}
}
class exception{
public
static
void main(String[] args){
Demo d=new Demo();
try{
int x = d.div(3, 1);//new
AritchmeticException()
System.out.println("x="+x);
}
catch (Exception e)
//Exception e =new AritchmeticException()
{
System.out.println("除零了")
;
System.out.println(e.getMessage());//BY
ZERO
System.out.println(e.toString());//异常名称:异常信息
e.printStackTrace();//异常名称 异常信息 异常位置
}
System.out.println("over");//
此语句运行,如果没有try catch不会执行
}
}
(2)通过throws方法代码举例
class Demo{
int div(int
a,int b)
throws Exception//
通过throws申明该功能可能出现问题
{
return(a/b);
}
}
class exception{
public
static
void main(String[] args){
Demo d=new Demo();
try{
int x = d.div(3, 1);//new
AritchmeticException()
System.out.println("x="+x);
}
catch (Exception e)
//Exception e =new AritchmeticException()
{
System.out.println("除零了")
;
System.out.println(e.getMessage());//BY
ZERO
System.out.println(e.toString());//异常名称:异常信息
e.printStackTrace();//异常名称 异常信息 异常位置
}
System.out.println("over");//
此语句运行,如果没有try catch不会执行
}
}
第四部分:自定义异常机制中throws与throw的区别
(1)throws用在函数上,throw用在函数内
(2)throws后面跟的异常类,可以跟多个,用逗号隔开 throw后面跟异常类
相关文章推荐
- 如何优雅地处理前端异常?
- C#异常处理详解
- JS异常处理的一个想法(sofish)
- PHP 的异常处理、错误的抛出及回调函数等面向对象的错误处理方法
- PHP如何抛出异常处理错误
- PHP中的错误处理、异常处理机制分析
- js中的异常处理try...catch使用介绍
- php5编程中的异常处理详细方法介绍
- php异常处理使用示例
- Asp.net Mvc 身份验证、异常处理、权限验证(拦截器)实现代码
- javascript 异常处理使用总结
- java多线程中的异常处理机制简析
- 深入理解Java编程中异常处理的优劣
- 分享一个php 的异常处理程序
- 深入剖析Java中的各种异常处理方式
- JS中的异常处理方法分享
- 一些.NET对多线程异常处理技巧分享
- c++异常处理机制示例及详细讲解
- MySQL异常处理浅析
- C++之异常处理详解