发布于 2018-02-26 23:54:55 | 135 次阅读 | 评论: 0 | 来源: 网友投递

这里有新鲜出炉的Java设计模式,程序狗速度看过来!

Java程序设计语言

java 是一种可以撰写跨平台应用软件的面向对象的程序设计语言,是由Sun Microsystems公司于1995年5月推出的Java程序设计语言和Java平台(即JavaEE(j2ee), JavaME(j2me), JavaSE(j2se))的总称。


这篇文章主要介绍了java 异常详解及应用实例的相关资料,需要的朋友可以参考下

java  异常

 异常的使用实例(异常分类:Error(是由JVM调用系统底层发生的,只能修改代码) 和 Exception(是JVM发生的,可以进行针对性处理))

 1.如果一个方法内可能出现异常,那么可以将异常通过throw的方式new 出相应的异常类,并在方法上   声明throws可能抛出的异常类抛给调用者,调用者可以进行异常捕获,或者继续抛出异常由 上层调用者继续处理,    如果整个过程都没有将异常进行任何处理,那么将由JVM虚拟机进行默认的处理 

2.调用者可以对异常进行try()catch(){}的异常处理, 也可以继续在方法后面throws该异常,catch代码块中    如果不处理也可以进行throw该异常

 3.运行时异常RuntimeException可以不进行显式的异常声明

 4.如果父类中的方法抛出了异常,如果子类对方法进行重写后也抛出异常,那么该异常必须不能大于父类的异常类, 如果父类中方法没有抛出异常,而子类中覆盖的方法却抛出了异常,那么此时只能进行try catch来捕获此异常,但是也可以将此异常在catch代码块中throw  new RuntimeExcetion()进行抛出,这样方法不用进行throws声明  

 5.很多时候异常并不需要调用者进行处理,调用者不一定具有处理能力

 6.异常应该包装成上层调用者可以识别的异常类型,面向不同的调用者,报告不同的异常信息,否者调用者不知道如何处理该异常

    在开发中这点十分重要

  7.finally代码块中常常进行资源的释放及关闭操作,对于打开的资源应该进行反方向的关闭操作,因为资源可能存在依赖性

  8.如果不进行声明异常,那么目的是不让调用者进行处理,让调用者的程序停止,这样必须修改错误代码


public class ExceptionDemo {

 public static void main(String[] args) {
 //OutOfMemoryError内存溢出错误,
 int[] i = new int[1024*1024*1024];
 System.out.println(i[1]);
 
 //ArrayIndexOutOfBoundsException索引越界异常
 int[] s = new int[2];
 System.out.println(s[2]);
 
 
 Calc calc = new Calc(); 
 //假如我们在这里捕获异常
 try {
  calc.run(4, 0);
  calc.run(4, -1);
 } catch (NegativeException e) {//必须先抛出异常的自定义子类
  e.printStackTrace();
  System.out.println(e.getMessage());
  //throw e;//可以继续将此异常抛出
 } catch (ArithmeticException e){//抛出自定义异常类的父类
  e.printStackTrace();
  System.out.println(e.getMessage());
  //throw e;
 } finally {
  System.out.println("finally肯定会执行到");
 }
 //如果上面进行了异常捕获,那么代码可以继续执行,否者代码不能继续执行
 System.out.println("可以执行到!");
 
 try {
  calc.run(4, -1);
  
 } catch (NegativeException e) {
  e.printStackTrace();
  System.out.println(e.getMessage());
  return;
 } finally {
  System.out.println("肯定会执行的");
 }
 System.out.println("执行不到了");//执行不到此行代码
 
 }

}

/**
 * 自定义异常
 */
class NegativeException extends ArithmeticException{
 public NegativeException() {
 }
 public NegativeException(String msg) {
 super(msg);
 }
}

interface AA{
 public abstract void method();
}

class Calc implements AA{
 //ArithmeticException其实为运行时异常(RuntimeException),即使不进行throws声明,也可以通过编译
 public int run(int m,int n)throws ArithmeticException,NegativeException{
 if(n==0){
  throw new ArithmeticException("除数不能为0");
 }else if(n<0){
  throw new NegativeException("除数不能为负数");
 }
 int s = m/n;
 return s ;
 }

 @Override
 public void method() {
 try {
  int p = 4/0;
 } catch (ArithmeticException e) {
  e.printStackTrace();
  throw new RuntimeException();//将异常继续抛出为运行时异常
 }
 }
}


感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!



最新网友评论  共有(0)条评论 发布评论 返回顶部

Copyright © 2007-2017 PHPERZ.COM All Rights Reserved   冀ICP备14009818号  版权声明  广告服务