java基础---异常

1.生活中的异常

正常情况下,小王每日开车去上班,耗时大约30分钟

但是,异常情况迟早要发生!

2.程序中的异常 

举例:

public class Test1 {

public static void main(String[] args) {

Scanner in = new Scanner(System.in);

System.out.print("请输入被除数:");

int num1 = in.nextInt();

System.out.print("请输入除数:");

int num2 = in.nextInt();

System.out.print("请输入除数:");

int num2 = in.nextInt();

System.out.println(String.format("%d / %d = %d",num1, num2, num1/ num2));

System.out.println("感谢使用本程序!");

}

}

3.什么是异常

异常是指在程序的运行过程中所发生的不正常的

事件,它会中断正在运行的程序

4.什么是异常处理

Java编程语言使用异常处理机制为程序提供了错误处理的能力

5.Java的异常处理是通过5个关键字来实现

trycatchfinallythrowthrows

捕获异常trycatchfinally

声明异常throws

抛出异常throw

 

举例:import java.util.Scanner;

public class Demo {

public static void main(String[] args) {

//算数异常

Scanner input=new Scanner(System.in);

System.out.println("输入被除数");

int a=input.nextInt();

System.out.println("输入除数");

try{

int b=input.nextInt();

int c= a/b;

System.out.println("结果"+c);

}catch(ArithmeticException e){

System.out.println("纳尼?除数不可以为0");}

}

6.使用try-catch块捕获异常,分为三种情况

第一种情况 :正常

public void method(){

try {

// 代码段(此处不会产生异常)

} catch (异常类型 ex) {

// 对异常进行处理的代码段

}

// 代码段

}

 

第二种情况:出现异常

public void method(){

try {

// 代码段 1

// 产生异常的代码段 2

// 代码段 3

} catch (异常类型 ex) {

// 对异常进行处理的代码段4

}

// 代码段5

}

 

第三种情况:异常类型不匹配

public void method(){ 发生异常

try {

// 代码段 1

// 产生异常的代码段 2

// 代码段 3

} catch (异常类型 ex) {

// 对异常进行处理的代码段4

}

// 代码段5

}

6.异常堆栈信息的打印(打印出错的位置

举例

import java.util.Scanner;

public class Demo1 {

public static void main(String[] args) {

//算数异常

Scanner input=new Scanner(System.in);

System.out.println("输入被除数");

int a=input.nextInt();

System.out.println("输入除数");

//快捷键    alt+shift+z

try{

int b=input.nextInt();

int c= a/b;

System.out.println("结果"+c);

}catch(ArithmeticException e){

System.out.println("纳尼?除数不可以为0");

//异常堆栈信息的打印--提示cuowu

e.printStackTrace();

}

System.out.println("10086");

}

}

 

7.快捷键

 alt+shift+z

8.异常对象常用的方法

void printStackTrace() 输出异常的堆栈信息

String getMessage() 返回异常信息描述字符串,是printStackTrace()输出信息的一部分

9.常见的异常类型               异常类型说明

Exception                            异常层次结构的父类

ArithmeticException            算术错误情形,如以零作除数

ArrayIndexOutOfBoundsException 数组下标越界

NullPointerException            尝试访问 null 对象成员

ClassNotFoundException     不能加载所需的类

IllegalArgumentExce            方法接收到非法参数

ClassCastException             对象强制类型转换出错

NumberFormatException      数字格式转换异常,如把"abc"转换成数字

10.try-catch-finally

try-catch块后加入finally

1.发生异常都执行  

2.不执行的唯一情况  System.exit(1)

10. 存在returntry-catch-finally

执行顺序   try发生异常---进入catch----执行finally----执行return退出方法

执行 ,先执行 try catch 块中的代码 然后执行finally 中的代码块, 如果存在return 字句 返回 catch 块中执行 return字句 退出

12.throwthrows

Throw 手动抛出异常 ,谁用谁处理

Throws 声明方法可能要 抛出的各种异常

举例:声明异常

import java.util.Scanner;

public class paochuyichang {

public static void main(String[] args) {

method();

}

//声明异常

public static void method() throws Exception{

Scanner input=new Scanner(System.in);

System.out.println("输入被除数");

int a=input.nextInt();

System.out.println("输入除数");

int b=input.nextInt();

int c= a/b;

System.out.println("结果"+c);

}

}

举例:抛出异常

package Demo;

public class Person {

private String name;

private String gender;

public void setGender(String gender) throws Exception{

if (gender.equals("")||gender.equals("")) {

this.gender=gender;

} else {

            //手动抛出异常

throw new Exception("对不起,性别只能是男或者女");

}

}

package Demo;

public class PeopleTest {

public static void main(String[] args) {

Person p=new Person();

try {

p.setGender("1");

} catch (Exception e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

}

}

13.异常的分类

 

14.throwthrows的区别是什么?

  throws写在参数旁边

  throw写在方法体里

15.练习

package lx;

public class Demo {

private int age;

public void setAge(int age) throws Exception {

if (age<100&&age>0) {

this.age=age;

} else {

throw new Exception("年龄必须在1-100");

}

}

}

 

package lx;

import java.util.Scanner;

public class DemoTest {

public static void main(String[] args) {

Scanner input=new Scanner(System.in);

Demo d=new Demo();

System.out.println("输入");

int age=input.nextInt();

try {

d.setAge(age);

} catch (Exception e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

}

16.多重catch

引发多种类型的异常

1-排列catch 语句的顺序:先子类后父类

2-发生异常时按顺序逐个匹配

3-只执行第一个与异常类型匹配的catch语句

 

 

练习:输出课程名称

package lx;

import java.util.Scanner;

public class Demo2 {

public static void main(String[] args) {

//数组越界

String[] course={"java","python","php"};

Scanner input=new Scanner(System.in);

System.out.println("请输入课程代码");

try {

int num=input.nextInt();

if (num==1) {

System.out.println(course[0]);

}else if(num==2){

System.out.println(course[1]);

}else if(num==3){

System.out.println(course[1]);

}else{

System.out.println(course[3]);

}

} catch (Exception e) {

// TODO Auto-generated catch block

System.out.println("对不起,没有者一项课程");

}finally{

System.out.println("欢迎提出意见");

}

}

}

17.开源日志记录工具log4j

实现以文件形式记录异常信息、程序正常运行

18.日志及分类

日志(log

1.主要用来记录系统运行中一些重要操作信息

2.便于监视系统运行情况,帮助用户提前发现和避开可能出现的问题,或者出现问题后根据日志找到原因

日志分类

SQL日志、异常日志、业务日志

log4j是一个非常优秀的开源日志记录工具

1.控制日志的输出级别

2.控制日志信息输送的目的地是控制台、文件等

3.控制每一条日志的输出格式

19.使用log4j记录日志步骤

  1. 在项目中加入log4jJAR文件

       工程...右键点击Build Path....Add External Archives...找到包的路径

  1. 创建log4j.properties文件

       在src....file.....创建log4j.properties文件

  1. 配置日志文件

### u8BBEu7F6ELoggeru8F93u51FAu7EA7u522Bu548Cu8F93u51FAu76EEu7684u5730 ###

log4j.rootLogger=debug, stdout,logfile

 

### u628Au65E5u5FD7u4FE1u606Fu8F93u51FAu5230u63A7u5236u53F0 ###

log4j.appender.stdout=org.apache.log4j.ConsoleAppender

log4j.appender.stdout.Target=System.err

log4j.appender.stdout.layout=org.apache.log4j.SimpleLayout

 

### u628Au65E5u5FD7u4FE1u606Fu8F93u51FAu5230u6587u4EF6uFF1Awxkj.log ###

log4j.appender.logfile=org.apache.log4j.FileAppender

log4j.appender.logfile.File=d:/first.log

log4j.appender.logfile.layout=org.apache.log4j.PatternLayout

log4j.appender.logfile.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss}%l %F %p %m%n

  1. 使用log4j记录日志信息

import java.util.Scanner;

import org.apache.log4j.Logger;

public class Log4jDemo {

//实例化一个log4j工具

private static Logger loger=Logger.getLogger(Log4jDemo.class.getName());

//异常日志  业务日志

public static void main(String[] args) {

Scanner input=new Scanner(System.in);

System.out.println("输入被除数");

int a=input.nextInt();

//记录日志

loger.debug("输入员一个被除数"+a);

try {

System.out.println("输入一个除数");

int b=input.nextInt();

loger.info("输入一个除数"+b);

int c=a/b;

System.out.println("结果是"+c);

loger.debug("结果是"+c);

}catch (Exception e) {

// TODO Auto-generated catch block

loger.error("出现除0异常");

e.printStackTrace();

}

}

}

原文地址:https://www.cnblogs.com/-lyr/p/9602578.html