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. [转]Asp.net MVC中的ViewData与ViewBag

    本文转自:http://www.cnblogs.com/wintersun/archive/2012/01/21/2328563.html 在Asp.net MVC 3 web应用程序中,我们会用到V ...

  2. 跨域策略文件crossdomain.xml文件

    使用crossdomain.xml让Flash可以跨域传输数据 一.crossdomain.xml文件的作用    跨域,顾名思义就是需要的资源不在自己的域服务器上,需要访问其他域服务器.跨域策略文件 ...

  3. C#程序执行时间

    Stopwatch类 using System.Diagnostics; static void Main(string[] args) { Stopwatch stopWatch = new Sto ...

  4. rest-framework框架——APIView和序列化组件

    一.快速实例 Quickstart http://www.cnblogs.com/yuanchenqi/articles/8719520.html restful协议 ---- 一切皆是资源,操作只是 ...

  5. SharePoint Designer - Workflow

    另一篇文章 SharePoint 2013 - Designer Workflow 1. Set field in current item : 不要连续多次使用,否则在发布时会出现unexpecte ...

  6. MD5简单实例

    如图当点击按钮时,会先判断是否第一次登陆,如果是第一次登陆登陆则会弹出设置密码的弹窗,若果登陆过则弹出登陆弹窗 其中输入的密码会用MD5加密下 package com.org.demo.wangfen ...

  7. Shell脚本批量修改图片尺寸

    #!/bin/sh function scandir(){ local cur_dir parent_dir workdir workdir=$ cd ${workdir} if [ ${workdi ...

  8. UIRecorder安装与使用

    继vue单元测试,将进行vue的e2e测试学习. 学习点: 安装uirecorder 用工具(UI Recorder)录制测试脚本 测试脚本的回放 本文意在安装UI Recorder,并且利用该工具进 ...

  9. LESS初体验

    将一个变量赋值给另一个变量,用引号:@white: 'color-white';,使用另一个变量,需要双@@符号:p {color: @@white;}. 而以这样进行变量的赋值:@white: @c ...

  10. 4.Zabbix 3.0 案例

    请查看我的有道云笔记: http://note.youdao.com/noteshare?id=2807c0910cd63d309e1462128a31ae0e&sub=241A94E5717 ...