9.异常Exception

9.1 异常概述


package exception;
/*
* 异常:程序运行的不正常情况
*
* Throwable: 异常的超类
* |-Error
* 严重问题,这种问题我们通过异常处理是不能搞定的,必须修改代码,如:内存溢出
* |-Exception
* |-运行期异常
* 程序运行期间,出现的异常,通过我们会通过修改代码来避免
* |-编译期异常
* 编写代码期间出现的错误,如果不处理,程序无法正常运行
*/
public class ExceptionDemo { public static void main(String[] args) {
divMethod(); }
//创建一个方法,该方法定义两个参数,参数a和参数b,实现除法操作
public static void divMethod(){
int a = 0;
int b = 0;
int p = a/b;
System.out.println("两数相除:"+p);
}
}


9.2 处理程序异常错误

9.2.1 程序异常由JVM处理

//将字符串转换成Integer对象
/*
* JVM是 如何默认处理异常的?
* 当出现异常的时候,JVM采取默认的处理方式
* 在控制台 输出 异常的名称 和 异常的原因 和 异常出现的位置
*
* 注意: 当异常出现的时候,JVM就会结束运行,下面的代码就不执行了,然后再控制台输出 异常的信息
*
* 这不是我们想要的效果, 自己来完成异常的处理
*/
public static void changeString(){
String str = "32536";
String stri = "aas8988";
System.out.println("将字符串转换成Integer类型:"+Integer.parseInt(str));
//程序运行到此句,出现异常,程序中断运行,上面一句输出打印仍然继续运行
System.out.println("将字符串转换成Integer类型:"+Integer.parseInt(stri));
}

9.2.2 捕捉异常,异常中的常用方法



/*
* 处理异常的方式
* 方式1: 自己处理异常
* 格式:
* try{
* 可能出现错误的代码
* } catch (异常类型 变量名) {// 变量名 其实就是一个异常对象
* 把异常解决掉
* } finally {
* 程序肯定要执行的代码
* 一般在这个位置进行 释放资源
* }
*
* 注意: 我不是让你错误隐藏, 让你处理错误
*
*
* 方式2: 把异常抛出,让别人来处理
*/
//方式1:自己处理异常
public static void exceptionMethod(){
int a = 0;
int b = 0;
int p = 0;
try {
p = a/b;//java.lang.ArithmeticException: / by zero
// new ArithmeticException("/ by zero");
} catch (ArithmeticException e) {//ArithmeticException e = new ArithmeticException("/ by zero");
System.out.println("除数不能为0!");
}finally{
System.out.println("try...catch语句不一定一定要Finally语句,但如果有finally那么久一定会执行,四种情况不执行,下面看");
}
//如果出现异常,那么输出打印p的初始化值,如果没有异常,输出正常结果
System.out.println("两数相除:"+p);
}



public static void exceptionMethods(){
String str = "32536";
String stri = "aas8988";
System.out.println("将字符串转换成Integer类型:"+Integer.parseInt(str));
//程序运行到此句,出现异常,程序中断运行,上面一句输出打印仍然继续运行
try {
System.out.println("将字符串转换成Integer类型:"+Integer.parseInt(stri));
} catch (Exception e) {
e.printStackTrace();
System.out.println(e.toString());
System.out.println(e.getMessage());
System.out.println("上面方法打印输出异常情况!");
System.exit(0);
}finally{
System.out.println("finally在四种情况中是不执行的!");
}

多个异常出现的解决:
/*
* 出现多个异常的时候,怎么办?
*
* 方式1: 把每一个异常单独处理
*
* 方式2: 把多个异常一起处理(一个try, 对应多个catch)
* 使用多个catch没每一个可能发生的异常进行处理
*
* 注意: 如果在try出现的异常,try中的代码不继续执行,跳转到对应catch 进行异常的处理
* 如果多个异常中,存在异常的继承关系, 子类的异常要放前面, 父类的异常放在最后
*
* jdk7的新特性:
* 平级异常
* catch (ArrayIndexOutOfBoundsException | ArithmeticException ... e) {...}
*/
//每一个异常单独处理
public static void test1(){
int a = 0;
int b = 3;
int p = 0;
String str = "asa898";
try {
p = b/a;
System.out.println(p);
} catch (Exception e) {
System.out.println(e.toString());
}
try {
System.out.println(Integer.parseInt(str));
} catch (Exception e) {
System.out.println(e.toString());
}
System.out.println("多个异常,把每一个异常单独处理!");
}
//多个异常一起处理,一个try,多个catch
public static void test2(){
int a = 0;
int b = 3;
int p = 0;
String str = "asa898";
try {
p = b/a;
System.out.println(p);
System.out.println(Integer.parseInt(str));
} catch (ArithmeticException e) {
e.printStackTrace();
}catch (NumberFormatException e) {
e.printStackTrace();
}
System.out.println("多个异常,一个try多个catch!");
}
//多个异常一起处理,平级异常
public static void test3(){
int a = 0;
int b = 3;
int p = 0;
String str = "asa898";
try {
p = b/a;
System.out.println(p);
System.out.println(Integer.parseInt(str));
} catch (ArithmeticException|NumberFormatException e) {
e.printStackTrace();
}
System.out.println("多个异常,平级异常!");
}

final finally finalize区别:
/*
* finally: 异常处理代码中一部分
* finally里面的代码肯定会执行
* 面试题
* 1、final、finally、finalize 请说明他们是什么?
*
* final: 修饰符
* 修饰变量,相当于是一个常量
* 修饰方法,不能被子类重写
* 修饰类, 不能被继承
*
* finally: 异常处理代码中一部分
* finally里面的代码肯定会执行
* 特殊情况: 如果在执行到finally之前,JVM就结束了,这时,finally不会执行
*
* finalize:
* 是Object类中的一个方法finalize(): 垃圾回收
*
* 2、 如果catch中存在return语句,问 finally语句会不会执行? 如果会,请输出在return前执行,还是return后执行?
* finally会执行,在return前执行
*
*/
public static void test4(){
//常被用作常量,如圆周率等,static不能在方法中使用
final int i = 0;
int a = 0;
int b = 3;
int p = 0;
//编译时错误,The final local variable i cannot be assigned. It must be blank and not using a compound assignment
// i = 7;
try {
p = b/a;
System.out.println(p);
} catch (Exception e) {
System.out.println("try中没有异常catch中不会运行!");
return;
}finally{
System.out.println("假如catch中有return,那么finally会在return之前被运行,finally运行完,运行return");
}
System.out.println("假如catch中有return,那么finally会在return之前被运行,finally运行完,运行return");
}

9.3.3 Java常见的异常


9.4 自定义异常




package exception.newCustomexception;
public class ScoreException extends Exception{
public ScoreException() {
super();
// TODO Auto-generated constructor stub
}
public ScoreException(String message) {
super(message);
// TODO Auto-generated constructor stub
}
}
package exception.newCustomexception;
public class Teacher {
//创建一个方法,该方法验证传入成绩
public static void checkScore(int score) throws ScoreException{
if(score<0 ||score>100){
throw new ScoreException("成绩不符合规范!");
}else {
System.out.println("成绩符合格式!");
}
}
}
package exception.newCustomexception; import java.util.Scanner; /*
* 自定义异常:
*
* 验证学生的成绩是否有效 0-100
*
* 创建一个自定义异常,需要继承Java中 提供的异常类 要么集合RuntimeException 或者 集合 Exception
*
* 继承RuntimeException异常
*/
public class MyException { public static void main(String[] args) throws ScoreException {
//输入学生成绩
Scanner sc = new Scanner(System.in);
System.out.println("请输入学生成绩:");
int score = sc.nextInt();
Teacher.checkScore(score);
} }

当然上面我们在MyExceptionDemo中采用的是throw处理异常的方式,我们还可以通过try...catch来解决异常!
9.5 抛出异常

9.5.1 使用throws关键字抛出异常


main函数 try {
test5();
} catch (Exception e) {
System.out.println(e.toString());
}
/*
* 异常处理方式:
* 方式2: 把异常抛出,让别人来处理
* 格式: 方法()小括号后面 加上 throws 异常类型
*
* 注意: 如果该方法有异常,抛出了, 那么,在调用该方法的这个人,需要处理该异常
*/
public static void test5() throws NumberFormatException{
String str = "asa898";
System.out.println(Integer.parseInt(str));
}

9.5.2 使用throw关键字抛出异常

9.6 运行时异常



9.7 异常的使用原则

package exception; import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date; /*
* 运行期的异常,可以通过修改代码来解决,没有必要使用异常处理(try..catch 或者 throws)
*
* 运行期异常: RuntimeException
* 编译期异常: Exception
*
* 那么我们学习的异常处理方式(二种) 是用来干什么呢? 用来针对非运行期的异常 的 异常类进行处理的
* 针对于编译期异常: Exception 使用
*/
public class ExceptionTest { public static void main(String[] args) {
//运行时异常可以通过修改代码来解决,不需要Try catch或者throws
method();
//编译时异常,在jdk中有一些类存在抛出异常,那么我们用这些类或方法时,也要记得处理异常
try {
method2();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
method3(); } //运行时异常
public static void method(){
// String str = "asd12345";
String str = "12345";
System.out.println(Integer.parseInt(str));
}
//编译时异常
public static void method2() throws ParseException{
String time = "2014-06-22 11:46:20";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSSSSSSS");
System.out.println(sdf.parse(time));
}
//编译时异常的第二种处理办法
public static void method3(){
String time = "2014-06-22 11:46:20";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSSSSSSS");
try {
Date date = sdf.parse(time);
} catch (ParseException e) {
// TODO Auto-generated catch block
System.out.println("异常的两种处理方式");
e.printStackTrace();
}
} }

9.异常Exception的更多相关文章
- Atitit java的异常exception 结构Throwable类
Atitit java的异常exception 结构Throwable类 1.1. Throwable类 2.StackTrace栈轨迹1 1.2. 3.cause因由1 1.3. 4.Suppres ...
- 05_Java异常(Exception)
1. 异常的概念 1.1什么是异常 异常指的是程序运行时出现的不正常情况. 1.2异常的层次 Java的异常类是处理运行时的特殊类,每一种异常对应一种特定的运行错误.所有Java异常类都是系统类库中E ...
- 异常Exception in thread "AWT-EventQueue-XX" java.lang.StackOverflowError
今天太背了,bug不断,检查到最后都会发现自己脑残了,粗心写错,更悲剧的是写错的时候还不提示错. 刚才有遇到一个问题,抛了这个异常Exception in thread "AWT-Event ...
- Sqoop异常:Exception in thread "main" java.lang.NoClassDefFoundError: org/json/JSONObject
18/12/07 01:09:03 INFO mapreduce.ImportJobBase: Beginning import of staffException in thread "m ...
- 异常 Exception 堆栈跟踪 异常捕获 MD
Markdown版本笔记 我的GitHub首页 我的博客 我的微信 我的邮箱 MyAndroidBlogs baiqiantao baiqiantao bqt20094 baiqiantao@sina ...
- 理解Python语言里的异常(Exception)
Exception is as a sort of structured "super go to".异常是一种结构化的"超级goto". 作为一个数十年如一日 ...
- PL/SQL 08 异常 exception
--PL/SQL错误 编译时 运行时 --运行时的出错处理 EXCEPTION --异常处理块DECLARE …BEGIN …EXCEPTION WHEN OTHERS THEN handle ...
- 【马克-to-win】学习笔记—— 第五章 异常Exception
第五章 异常Exception [学习笔记] [参考:JDK中文(类 Exception)] java.lang.Object java.lang.Throwable java.lang.Except ...
- 【异常】Maxwell异常 Exception in thread "main" net.sf.jsqlparser.parser.TokenMgrError: Lexical error at line 1, column 596. Encountered: <EOF> after : ""
1 详细异常 Exception in thread "main" net.sf.jsqlparser.parser.TokenMgrError: Lexical error at ...
- 异常-Exception in thread "main" net.sf.jsqlparser.parser.TokenMgrError: Lexical error at line 1, column 596. Encountered: <EOF> after :
1 详细异常 Exception in thread "main" net.sf.jsqlparser.parser.TokenMgrError: Lexical error at ...
随机推荐
- 一个C#后台调用接口的例子
string url = ConfigurationSettings.AppSettings["resurl"].ToString(); var wc = new WebClien ...
- Git代码merge
Git代码合并遇到如下问题: <<<<<<< HEAD client.post(url, secretKey, function (data, res ...
- IO流之Properties类
Properties类介绍 Properties 类表示了一个持久的属性集.Properties 可保存在流中或从流中加载.属性列表中每个键及其对应值都是一个字符串. 特点: 1.Hashtable的 ...
- 如何使用CSS隐藏滚动条并且兼容大部分浏览器
隐藏滚动条,已经自己实测在浏览器Chrome, IE (6+), Firefox, Opera, Safari. 如下demo: Content 1 Content 1 Content 1 Conte ...
- String字符串操作
char chars[] ={'a','b','c'}; String s = new String(chars); int len = s.length();//字符串长度 System.out.p ...
- .NET开源工作流RoadFlow-表单设计-保存与发布
表单的过程中可以随时保存,以便下次继续设计. 表单设计完成后即可点击发布按钮,发布表单,发布表单后即可在流程设计时选定该表单.
- mybooklist.cn 书单de故事六月十六日
1.我的30年30本书 刘苏里书单北京万圣书园总经理,以经营人文社科类图书著称.生于1960年,1983年毕业于北京大学国际政治系,1986年毕业于中国政法大学研究生院.
- 通过 PowerShell 的方式增加虚拟机终结点
关于虚拟机终结点的概念请阅读:如何设置虚拟机的终结点 本文包含以下内容(本文在名称为"pstest"的虚拟机做测试): 通过 PowerShell 的方式增加终结点 通过 Powe ...
- Hive的UDF(用户自定义函数)开发
当 Hive 提供的内置函数无法满足你的业务处理需要时,此时就可以考虑使用用户自定义函数(UDF:user-defined function). 测试各种内置函数的快捷方法: 创建一个 dual 表 ...
- HDU2054:A == B ?
A == B ? Time Limit: 1000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Su ...