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的更多相关文章

  1. Atitit java的异常exception 结构Throwable类

    Atitit java的异常exception 结构Throwable类 1.1. Throwable类 2.StackTrace栈轨迹1 1.2. 3.cause因由1 1.3. 4.Suppres ...

  2. 05_Java异常(Exception)

    1. 异常的概念 1.1什么是异常 异常指的是程序运行时出现的不正常情况. 1.2异常的层次 Java的异常类是处理运行时的特殊类,每一种异常对应一种特定的运行错误.所有Java异常类都是系统类库中E ...

  3. 异常Exception in thread "AWT-EventQueue-XX" java.lang.StackOverflowError

    今天太背了,bug不断,检查到最后都会发现自己脑残了,粗心写错,更悲剧的是写错的时候还不提示错. 刚才有遇到一个问题,抛了这个异常Exception in thread "AWT-Event ...

  4. 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 ...

  5. 异常 Exception 堆栈跟踪 异常捕获 MD

    Markdown版本笔记 我的GitHub首页 我的博客 我的微信 我的邮箱 MyAndroidBlogs baiqiantao baiqiantao bqt20094 baiqiantao@sina ...

  6. 理解Python语言里的异常(Exception)

    Exception is as a sort of structured "super go to".异常是一种结构化的"超级goto". 作为一个数十年如一日 ...

  7. PL/SQL 08 异常 exception

    --PL/SQL错误  编译时  运行时 --运行时的出错处理  EXCEPTION --异常处理块DECLARE …BEGIN …EXCEPTION WHEN OTHERS THEN  handle ...

  8. 【马克-to-win】学习笔记—— 第五章 异常Exception

    第五章 异常Exception [学习笔记] [参考:JDK中文(类 Exception)] java.lang.Object java.lang.Throwable java.lang.Except ...

  9. 【异常】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 ...

  10. 异常-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 ...

随机推荐

  1. 深入理解JavaScript系列(32):设计模式之观察者模式

    介绍 观察者模式又叫发布订阅模式(Publish/Subscribe),它定义了一种一对多的关系,让多个观察者对象同时监听某一个主题对象,这个主题对象的状态发生变化时就会通知所有的观察者对象,使得它们 ...

  2. 从零开始写C# MVC框架之--- 项目结构

    框架总分2个项目:Web开发项目.帮助类项目 (ZyCommon.Zy.Utilities) 1.ZyCommon,是Web开发项目结构.新建一个空解决方案,再建Data.Service.ZyWeb解 ...

  3. IIS7部署网站出现500.19错误(权限不足)的解决方案

    错误摘要 HTTP 错误 500.19 - Internal Server Error 无法访问请求的页面,因为该页的相关配置数据无效. 详细错误信息 模块 IIS Web Core 通知 未知 处理 ...

  4. 如何取得GridView被隐藏列的值

    如何取得GridView被隐藏列的值         分类:             ASP.net              2009-06-25 12:47     943人阅读     评论(1 ...

  5. Python中and和or的运算法则

    1. 在纯and语句中,如果每一个表达式都不是假的话,那么返回最后一个,因为需要一直匹配直到最后一个.如果有一个是假,那么返回假2. 在纯or语句中,只要有一个表达式不是假的话,那么就返回这个表达式的 ...

  6. IE8按F12开发人员工具不显示

    一直不喜欢用IE,不过为了项目需要,不得不使用IE 而且此功能只支持IE8,(⊙﹏⊙)b) 当按F12调出开发人员工具的时候发现显示不出来了,在任务栏里有显示,将鼠标放在任务栏的开发人员工具上, 背景 ...

  7. 吐槽中小民营IT企业管理七宗罪

    傲慢.妒忌.暴怒.懒惰.贪婪.贪食及色欲,电影<七宗罪>中借七个典型的命案告诉我们,人性中最丑陋的七大恶行.在实际的工作中自己对企业的经营和日常管理有了一些更深刻的认识,偏偏自己又是一个很 ...

  8. k-近邻算法(kNN)

    1.算法工作原理 存在一个训练样本集,我们知道样本集中的每一个数据与所属分类的对应关系,输入没有标签的新数据后,将新数据的每个特征与样本集中数据对应特征进行比较,然后算法提取样本集中特征最相似的数据( ...

  9. 任务六:通过HTML及CSS模拟报纸排版

    任务目的 深入掌握CSS中的字体.背景.颜色等属性的设置 进一步练习CSS布局 任务描述 参考 PDS设计稿(点击下载),实现页面开发,要求实现效果与 样例(点击查看) 基本一致 页面中的各字体大小, ...

  10. June 14th 2017 Week 24th Wednesday

    Love looks not with the eyes, but with the mind. 爱,不在眼里,而在心中. Staring in her eyes and you will find ...