赞
踩
- package com.exception;
-
- public class Demo01 {
- public static void main(String[] args) {
- System.out.println(11/0); //除数不能为0
- System.out.println() //没有分号
- }
- }
创建Text(捕获错误):
- package com.exception;
-
- public class Test {
- public static void main(String[] args) {
- int a = 1;
- int b = 0;
- try {
- System.out.println(a/b);
- }catch (ArithmeticException e){
- System.out.println(e+"出现异常,b不能为0");
- }finally {//处理善后工作
- System.out.println("finally");
- }
- try {
- new Test().a();
- }
- //捕获异常要从小到大的取捕获
- catch (Error e){
- System.out.println(e+"Error");
- }catch (Exception e){
- System.out.println(e+"调用Exception");
- } catch (Throwable e){
- System.out.println(e+":Throwable");
- }finally {
- System.out.println("a方法调用b方法,b方法调用a方法");
- }
- //finally,可以不要finally,假设IO,资源,关闭!
-
- }
- public void a(){
- b();
- }
- public void b(){
- a();
- }
- }

创建Text2(主动抛出异常):
- package com.exception;
-
- public class Test2 {
-
- public static void main(String[] args) {
-
- int a = 1;
- int b = 2;
- try {
- new Test2().test(1,0);
- } catch (Exception e) {
- e.printStackTrace();
- }
-
-
- //快捷键 Ctrl+Alt+T
- try {
- System.out.println(a/b);
- } catch (Exception e) {
- e.printStackTrace();//打印错误的栈信息
- } finally {
- }
-
-
- try {
- if (b==0){
- throw new ArithmeticException(); //主动抛出异常
- }
- } catch (Exception e) {
- e.printStackTrace();
- System.out.println("if里的语句");
- }
-
- }
- public void test(int a,int b)throws ArithmeticException{
- if (b==0) {
- throw new ArithmeticException(); //主动抛出异常,一般用在方法中
- }
- }
-
- }

狂神说java的原版和自己的理解写出来的。
加油!:
难得上进一次,不能半途而废。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。