一、注解
1. 注解概述
注解是以“@注释名”在代码中存在的,还可以添加一些参数值,例如:
@SuppressWarnings(value=”unchecked”)
@Override
@Deprecated
@Test
@author
@param
....
注解Annotation是从JDK5.0开始引入。
虽然说注解也是一种注释,因为它们都不会改变程序原有的逻辑,只是对程序增加了某些注释性信息。不过它又不同于单行注释和多行注释,对于单行注释和多行注释是给程序员看的,而注解是可以被编译器或其他程序读取的一种注释,程序还可以根据注解的不同,做出相应的处理。
一个完整的注解有三个部分:
1)注解的声明:就如同类、方法、变量等一样,需要先声明后使用
2)注解的使用:用于注解在包、类、方法、属性、构造、局部变量等上面的10个位置中一个或多个位置
3)注解的读取:有一段专门用来读取这些使用的注解,然后根据注解信息作出相应的处理,这段程序称为注解处理流程,这也是注解区别与普通注释最大的不同。
2. 系统定义的三个基本注解
1)@Override
- 用于检测被修饰的方法为有效的重写方法,如果不是,则报编译错误
- 只能标记在方法上
- 它会被编译器程序读取
2)@Deprecated
- 用于表示被标记的数据已经过时,不建议使用
- 可以用于修饰属性、方法、构造、类、包、局部变量、参数
- 它会被编译器程序读取
3)@SuppressWarnings
- 抑制编译警告
- 可以用于修饰类、属性、方法、构造、局部变量、参数
- 它会被编译器程序读取
示例代码:
public class TestAnnotation {
@SuppressWarnings({"unused","rawtypes", "unchecked"})
public static void main(String[] args) {
int i;
List list = new ArrayList();
list.add("");
list.add(123);
list.add("");
Father f = new Son();
f.show();
f.methodOl();
}
}
class Father{
@Deprecated
public void show() {
}
public void methodOl() {
System.out.println("Father Method");
}
public void print1n(){
System.out.println("Father Method");
}
public int sum(int... nums){
int sum = 0;
for (int i = 0; i < nums.length; i++) {
sum += nums[i];
}
return sum;
}
}
class Son extends Father{
@Override
public void method01() {
System.out.println("Son Method");
}
@Override
public void println(){
System.out.println("Father Method");
}
@Override
public long sum(int[] nums){
int sum = 0;
for (int i = 0; i < nums.length; i++) {
sum += nums[i];
}
return sum;
}
}
3. 自定义注解(了解)
JDK1.5在java.lang.annotation包定义了4个标准的meta-annotation类型,它们被用来提供对其它 annotation类型作说明。
1)@Target:用于描述注解的使用范围
- 可以通过枚举类型ElementType的10个常量对象来指定
- TYPE,METHOD,CONSTRUCTOR,PACKAGE…
2)@Retention:用于描述注解的生命周期
- 可以通过枚举类型RetentionPolicy的3个常量对象来指定
- SOURCE(源代码)、CLASS(字节码)、RUNTIME(运行时)
- 唯有RUNTIME阶段才能被反射读取到。
3)@Documented:表明这个注解应该被 javadoc工具记录。
4)@Inherited:允许子类继承父类中的注解
系统注解代码:
package java.lang;
import java.lang.annotation.*;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.SOURCE)
public @interface Override {
}
package java.lang;
import java.lang.annotation.*;
import static java.lang.annotation.ElementType.*;
@Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE})
@Retention(RetentionPolicy.SOURCE)
public @interface SuppressWarnings {
String[] value();
}
package java.lang;
import java.lang.annotation.*;
import static java.lang.annotation.ElementType.*;
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(value={CONSTRUCTOR, FIELD, LOCAL_VARIABLE, METHOD, PACKAGE, PARAMETER, TYPE})
public @interface Deprecated {
}
自定义注解代码:
package com.drimwai.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
public class TestDefineAnnotation {
public static void main(String[] args) {
//读取注解信息
MyAnnotation my = MyClass.class.getAnnotation(MyAnnotation.class);
System.out.println(my.value());
}
}
@MyAnnotation("Drimwai")
class MyClass{
}
@Documented
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation{
String value() default "Drimwai";
}
二、异常
1. 异常概述
在使用计算机语言进行项目开发的过程中,即使程序员把代码写得 尽善尽美,在系统的运行过程中仍然会遇到一些问题,因为很多问题不是靠代码能够避免的,比如:客户输入数据的格式,读取文件是否存在,网络是否始终保持通畅等等。
异常 :指的是程序在执行过程中,出现的非正常的情况,如果不处理最终会导致JVM的非正常停止。
异常指的并不是语法错误,语法错了,编译不通过,不会产生字节码文件,根本不能运行。
异常也不是指逻辑代码错误而没有得到想要的结果,例如:求a与b的和,你写成了a-b
对于异常,一般有两种解决方法:一是遇到错误就终止程序的运行。另一种方法是由程序员在编写程序时,就考虑到错误的检测、错误消息的提示,以及错误的处理。
Java中是如何表示不同的异常情况,又是如何让程序员得知,并处理异常的呢?
Java中把不同的异常用不同的类表示,一旦发生某种异常,就通过创建该异常类型的对象,并且抛出,然后程序员可以catch到这个异常对象,并处理,如果无法catch到这个异常对象,那么这个异常对象将会导致程序终止。
2. 异常体系
异常的根类是java.lang.Throwable
,其下有两个子类:java.lang.Error
与java.lang.Exception
,平常所说的异常指java.lang.Exception
。
2.1. Throwable体系:
Error:严重错误Error,无法通过处理的错误,只能事先避免。例如:StackOverflowError和OOM(OutOfMemoryError)。
Exception:表示异常,其它因编程错误或偶然的外在因素导致的一般性问题,程序员可以通过代码的方式纠正,使程序继续运行,是必须要处理的。例如:空指针访问、试图读取不存在的文件、网络连接中断、数组角标越界
2.2. Throwable中的常用方法:
1)public void printStackTrace()
:打印异常的详细信息。
包含了异常的类型,异常的原因,还包括异常出现的位置,在开发和调试阶段,都得使用printStackTrace。
2)public String getMessage()
:获取发生异常的原因。
提示给用户的时候,就提示错误原因。
出现异常,不要紧张,把异常的简单类名,拷贝到API中去查。
3. 异常分类
我们平常说的异常就是指Exception,因为这类异常一旦出现,我们就要对代码进行更正,修复程序。
异常(Exception)的分类:根据在编译时期还是运行时期去检查异常?
1)编译时期异常: checked异常。在编译时期,就会检查,如果没有处理异常,则编译失败。(如文件找不到异常)
2)运行时期异常: runtime异常。在运行时期,检查异常.在编译时期,运行异常不会被编译器检测到(不报错)。(如数组索引越界异常,类型转换异常)。程序员应该积极避免其出现的异常,而不是使用try…catch处理,因为这类异常很普遍,若都使用try…catch或throws处理可能会对程序的可读性和运行效率产生影响。
3.1. VirtualMachineError
最常见的就是:StackOverflowError、OutOfMemoryError
@Test
public void test01(){
//StackOverflowError
digui();
}
public void digui(){
digui();
}
@Test
public void test02(){
//OutOfMemoryError
//方式一:
int[] arr = new int[Integer.MAX_VALUE];
}
@Test
public void test03(){
//OutOfMemoryError
//方式二:
StringBuilder s = new StringBuilder();
while(true){
s.append("atguigu");
}
}
3.2. 运行时异常
@Test
public void test01(){
//NullPointerException
int[][] arr = new int[3][];
System.out.println(arr[0].length);
}
@Test
public void test02(){
//ClassCastException
Person p = new Man();
Woman w = (Woman) p;
}
@Test
public void test03(){
//ArrayIndexOutOfBoundsException
int[] arr = new int[5];
for (int i = 1; i <= 5; i++) {
System.out.println(arr[i]);
}
}
@Test
public void test04(){
//InputMismatchException
Scanner input = new Scanner(System.in);
System.out.print("请输入一个整数:");
int num = input.nextInt();
}
@Test
public void test05(){
int a = 1;
int b = 0;
//ArithmeticException
System.out.println(a/b);
}
3.3. 编译时异常
@Test
public void test06() {
Thread.sleep(1000);//休眠1秒
}
@Test
public void test07() {
FileInputStream fis = new FileInputStream("Java学习秘籍.txt");
}
@Test
public void test08() {
Connection conn = DriverManager.getConnection("....");
}
4. 异常抛出机制
先运行下面的程序,程序会产生一个数组索引越界异常ArrayIndexOfBoundsException。我们通过图解来解析下异常产生的过程。
工具类
public class ArrayTools {
// 对给定的数组通过给定的角标获取元素。
public static int getElement(int[] arr, int index) {
int element = arr[index];
return element;
}
}
测试类
public class ExceptionDemo {
public static void main(String[] args) {
int[] arr = { 34, 12, 67 };
int num = ArrayTools.getElement(arr, 4)
System.out.println("num=" + num);
System.out.println("over");
}
}
上述程序执行过程图解:
5. 异常处理
Java异常处理的五个关键字:throw、throws、try、catch、finally
5.1. 抛出throw
Java程序的执行过程中如出现异常,会生成一个异常类对象,该异常对象将被提交给Java运行时系统,这个过程称为抛出(throw)异常。异常对象的生成有两种方式:
1)由虚拟机自动生成:程序运行过程中,虚拟机检测到程序发生了问题,如果在当前代码中没有找到相应的处理程序,就会在后台自动创建一个对应异常类的实例对象并抛出——自动抛出
2)由开发人员手动创建:Exception exception = new ClassCastException();——创建好的异常对象不抛出对程序没有任何影响,和创建一个普通对象一样,但是一旦throw抛出,就会对程序运行产生影响了。
下面我们说明手动抛出异常:
比如,在定义方法时,方法需要接受参数。那么,当调用方法使用接受到的参数时,首先需要先对参数数据进行合法的判断,数据若不合法,就应该告诉调用者,这时可以使用抛出异常的方式来告诉调用者。
在java中,提供了一个throw关键字,它用来抛出一个指定的异常对象。那么,抛出一个异常具体如何操作呢?
1)创建一个异常对象。封装一些提示信息(信息可以自己编写)。
2)需要将这个异常对象告知给调用者。怎么告知呢?怎么将这个异常对象传递到调用者处呢?通过关键字throw就可以完成。throw 异常对象。
3)throw用在方法内,用来抛出一个异常对象,将这个异常对象传递到调用者处,并结束当前方法的执行。
使用格式:
throw new 异常类名(参数);
所有的Java内置的运行时异常有两个构造方法:一个没有参数,一个带有一个字符串参数。
当用第二种形式时,参数指定描述异常的字符串。如果对象用作 print( ) 或者 println( ) 的参数 时,该字符串被显示。这同样可以通过调用getMessage( )来实现,getMessage( )是由 Throwable 定义的。
例如:
throw new NullPointerException("要访问的arr数组不存在");
throw new ArrayIndexOutOfBoundsException("该索引在数组中不存在,已超出范围");
学习完抛出异常的格式后,我们通过下面程序演示下throw的使用。
public class ThrowDemo {
public static void main(String[] args) {
//创建一个数组
int[] arr = {2,4,52,2};
//根据索引找对应的元素
int index = 4;
int element = getElement(arr, index);
System.out.println(element);
System.out.println("over");
}
/*
* 根据 索引找到数组中对应的元素
*/
public static int getElement(int[] arr,int index){
if(arr == null){
/*
判断条件如果满足,当执行完throw抛出异常对象后,方法已经无法继续运算。
这时就会结束当前方法的执行,并将异常告知给调用者。这时就需要通过异常来解决。
*/
throw new NullPointerException("要访问的arr数组不存在");
}
//判断 索引是否越界
if(index<0 || index>arr.length-1){
/*
判断条件如果满足,当执行完throw抛出异常对象后,方法已经无法继续运算。
这时就会结束当前方法的执行,并将异常告知给调用者。这时就需要通过异常来解决。
*/
throw new ArrayIndexOutOfBoundsException("哥们,角标越界了~~~");
}
int element = arr[index];
return element;
}
}
5.2. 声明异常throws
声明异常:将问题标识出来,报告给调用者。如果方法内通过throw抛出了编译时异常,而没有捕获处理(稍后讲解该方式),那么必须通过throws进行声明,让调用者去处理。
关键字throws运用于方法声明之上,用于表示当前方法不处理异常,而是提醒该方法的调用者来处理异常(抛出异常).
声明异常格式:
修饰符 返回值类型 方法名(参数) throws 异常类名1,异常类名2…{ }
声明异常的代码演示:
import java.io.File;
import java.io.FileNotFoundException;
public class TestException {
public static void main(String[] args) throws FileNotFoundException {
readFile("不敲代码学会Java秘籍.txt");
}
// 如果定义功能时有问题发生需要报告给调用者。可以通过在方法上使用throws关键字进行声明
public static void readFile(String filePath) throws FileNotFoundException{
File file = new File(filePath);
if(!file.exists()){
throw new FileNotFoundException(filePath+"文件不存在");
}
}
}
throws用于进行异常类的声明,若该方法可能有多种异常情况产生,那么在throws后面可以写多个异常类,用逗号隔开。
import java.io.File;
import java.io.FileNotFoundException;
public class TestException {
public static void main(String[] args) throws FileNotFoundException,IllegalAccessException {
readFile("不敲代码学会Java秘籍.txt");
}
// 如果定义功能时有问题发生需要报告给调用者。可以通过在方法上使用throws关键字进行声明
public static void readFile(String filePath) throws FileNotFoundException,IllegalAccessException{
File file = new File(filePath);
if(!file.exists()){
throw new FileNotFoundException(filePath+"文件不存在");
}
if(!file.isFile()){
throw new IllegalAccessException(filePath + "不是文件,无法直接读取");
}
//...
}
}
throws 抛出异常的规则:
- 如果是不受检查异常( unchecked exception ),即 Error 、 RuntimeException 或它们的子类,那么可以不使用 throws 关键字来声明要抛出的异常,编译仍能顺利通过,但在运行时会被系统抛出。
- 必须声明方法可抛出的任何检查异常( checked exception )。即如果一个方法可能出现受可查异常,要么用 try-catch 语句捕获,要么用 throws 子句声明将它抛出,否则会导致编译错误
- 仅当抛出了异常,该方法的调用者才必须处理或者重新抛出该异常。当方法的调用者无力处理该异常的时候,应该继续抛出,而不是囫囵吞枣。
- 调用方法必须遵循任何可查异常的处理和声明规则。若覆盖一个方法,则不能声明与覆盖方法不同的异常。声明的任何异常必须是被覆盖方法所声明异常的同类或子类。
5.3. 捕获异常try…catch
捕获异常语法如下:
try{
编写可能会出现异常的代码
}catch(异常类型1 e){
处理异常的代码
//记录日志/打印异常信息/继续抛出异常
}catch(异常类型2 e){
处理异常的代码
//记录日志/打印异常信息/继续抛出异常
}
....
**try:**该代码块中编写可能产生异常的代码。
**catch:**用来进行某种异常的捕获,实现对捕获到的异常进行处理。
1)可以有多个catch块,按顺序匹配。
2)如果多个异常类型有包含关系,那么小上大下
演示如下:
public class TestException {
public static void main(String[] args) {
try {
readFile("不敲代码学会Java秘籍.txt");
} catch (FileNotFoundException e) {
// e.printStackTrace();
// System.out.println("好好敲代码,不要老是想获得什么秘籍");
System.out.println(e.getMessage());
} catch (IllegalAccessException e) {
e.printStackTrace();
}
System.out.println("继续学习吧...");
}
// 如果定义功能时有问题发生需要报告给调用者。可以通过在方法上使用throws关键字进行声明
public static void readFile(String filePath) throws FileNotFoundException, IllegalAccessException{
File file = new File(filePath);
if(!file.exists()){
throw new FileNotFoundException(filePath+"文件不存在");
}
if(!file.isFile()){
throw new IllegalAccessException(filePath + "不是文件,无法直接读取");
}
//...
}
}
如何获取异常信息:
Throwable类中定义了一些查看方法:
1)public String getMessage()
:获取异常的描述信息,原因(提示给用户的时候,就提示错误原因。
2)public void printStackTrace()
:打印异常的跟踪栈信息并输出到控制台。
注意:包含了异常的类型,异常的原因,还包括异常出现的位置,在开发和调试阶段,都得使用printStackTrace。
5.4. finally块
finally:有一些特定的代码无论异常是否发生,都需要执行。另外,因为异常会引发程序跳转,导致有些语句执行不到。而finally就是解决这个问题的,在finally代码块中存放的代码都是一定会被执行的。
什么时候的代码必须最终执行?
当我们在try语句块中打开了一些物理资源(磁盘文件/网络连接/数据库连接等),我们都得在使用完之后,最终关闭打开的资源。
finally的语法:
try{
}catch(...){
}finally{
无论try中是否发生异常,也无论catch是否捕获异常,也不管try和catch中是否有return语句,都一定会执行
}
或
try{
}finally{
无论try中是否发生异常,也不管try中是否有return语句,都一定会执行
}
注意:finally不能单独使用。
比如在我们之后学习的IO流中,当打开了一个关联文件的资源,最后程序不管结果如何,都需要把这个资源关闭掉。
finally代码参考如下:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class TestException {
public static void main(String[] args) {
readFile("不敲代码学会Java秘籍.txt");
System.out.println("继续学习吧...");
}
// 如果定义功能时有问题发生需要报告给调用者。可以通过在方法上使用throws关键字进行声明
public static void readFile(String filePath) {
File file = new File(filePath);
FileInputStream fis = null;
try {
if(!file.exists()){
throw new FileNotFoundException(filePath+"文件不存在");
}
if(!file.isFile()){
throw new IllegalAccessException(filePath + "不是文件,无法直接读取");
}
fis = new FileInputStream(file);
//...
} catch (Exception e) {
//抓取到的是编译期异常 抛出去的是运行期
throw new RuntimeException(e);
}finally{
System.out.println("无论如何,这里的代码一定会被执行");
try {
if(fis!=null){
fis.close();
}
} catch (IOException e) {
//抓取到的是编译期异常 抛出去的是运行期
throw new RuntimeException(e);
}
}
}
}
当只有在try或者catch中调用退出JVM的相关方法,例如System.exit(0),此时finally才不会执行,否则finally永远会执行。
5.5. finally与return
形式一:从try回来
public class TestReturn {
public static void main(String[] args) {
int result = test("12");
System.out.println(result);
}
public static int test(String str){
try{
Integer.parseInt(str);
return 1;
}catch(NumberFormatException e){
return -1;
}finally{
System.out.println("test结束");
}
}
}
形式二:从catch回来
public class TestReturn {
public static void main(String[] args) {
int result = test("a");
System.out.println(result);
}
public static int test(String str){
try{
Integer.parseInt(str);
return 1;
}catch(NumberFormatException e){
return -1;
}finally{
System.out.println("test结束");
}
}
}
形式三:从finally回来
public class TestReturn {
public static void main(String[] args) {
int result = test("a");
System.out.println(result);
}
public static int test(String str){
try{
Integer.parseInt(str);
return 1;
}catch(NumberFormatException e){
return -1;
}finally{
System.out.println("test结束");
return 0;
}
}
}
try, catch,finally ,return 执行顺序:
执行try,catch , 给返回值赋值
执行finally
return
5.6. 自定义异常
使用Java内置的异常类可以描述在编程时出现的大部分异常情况。除此之外,用户还可以自定义异常。 用户自定义异常类,只需继承 Exception 类即可。
在程序中使用自定义异常类,大体可分为以下几个步骤:
- 创建自定义异常类。
- 在方法中通过 throw 关键字抛出异常对象。
- 如果在当前抛出异常的方法中处理异常,可以使用 try-catch 语句捕获并处理;否则在方法的声明处通过 throws 关键字指明要抛出给方法调用者的异常,继续进行下一步操作。
- 在出现异常方法的调用者中捕获并处理异常。
【举例:】
class MyException extends Exception {
private int detail;
MyException(int a){
detail = a;
}
public String toString(){
return "MyException ["+ detail + "]";
}
}
public class TestMyException {
static void compute(int a) throws MyException {
System.out.println("Called compute(" + a + ")");
if (a > 10) {
throw new MyException(a);
}
System.out.println("Normal exit!");
}
public static void main(String[] args) {
try {
compute(1);
compute(20);
} catch (MyException me) {
System.out.println("Caught " + me);
}
}
}
实际应用中的经验与总结:
处理运行时异常时,采用逻辑去合理规避同时辅助try-catch处理
在多重catch块后面,可以加一个catch ( Exception )来处理可能会被遗漏的异常
对于不确定的代码,也可以加上try-catch,处理潜在的异常
尽量去处理异常,切忌只是简单的调用printStackTrace)去打印输出
具体如何处理异常,要根据不同的业务需求和异常类型去决定
尽量添加finally语句块去释放占用的资源
The End!!创作不易,欢迎点赞/评论!!欢迎关注个人公众号