第五章:异常处理(代码片段)

二十的十七 二十的十七     2022-12-22     715

关键词:

第五章:异常处理知识梳理

本章内容分为:异常处理概述、try-catch处理异常、throw和throws、自定义异常。

5.1异常处理概述

问题:为什么要异常处理???
编程中我们常说没有完美的代码,几乎每个应用程序都有这样或那样的小问题,异常并不可怕,只要在编程中预先考虑到可能出现问题的代码,然后加以处理就可以避免异常。

那么程序中如果遇到了异常会怎么样呢?会直接终止程序的运行,下面我们就来看看程序中的异常:

package com.exception;

public class Mytest1 

	public static void main(String[] args) 
		// TODO Auto-generated method stub
        String str=null;
        str.toString();
	




这里出现了一个空指针的异常(nullpointerexception)。

问题:如果中间出现了异常,后面是否还会正常执行?请看下面代码:

package com.exception;

public class Mytest1 

	public static void main(String[] args) 
		// TODO Auto-generated method stub
		System.out.println("第1步");
		System.out.println("第2步");
        String str=null;
        str.toString();
		System.out.println("第3步");
		System.out.println("第4步");
	




如上代码可知答案:如果中间出现了异常,后面将无法执行。

问题来了,那我们怎么样来处理让它不崩溃呢?所以要进行我们的异常处理,当然在程序运行过程中会出现很多种不同异常,比如说我们的nullpointerexception就是空指针异常,还有下标越界异常。

package com.exception;

public class Mytest1 

	public static void main(String[] args) 
		// TODO Auto-generated method stub
		String[]strs= "11","22";
		System.out.println(strs[2]);
	




注释:arrayindexoutofboundsexception是数组的下标越界异常。

还有一种算数异常:

package com.exception;

public class Mytest1 

	public static void main(String[] args) 
		// TODO Auto-generated method stub
		System.out.println(5/0);
	



注释:arithmeticexception是算数的异常。

对5.1进行一个小节:一旦出现了运行时异常,程序将终止运行,所以我们就必须要对这种可能出现异常代码进行一个异常捕获处理。

5.2try-catch异常处理
在Java中最顶级的异常处理叫THROWABLE,它下面又分为ERROR异常(一般指系统或硬件级别的异常,我们的Java程序不能处理)和EXCEPTION异常。

(1) 在Java中完成异常的处理一般有两种方式:一种是try catch finally三个关键字,另一种是throw和throws。

下面我们先来看看TRY CATCH FINALLY的使用:

第一个案例:

package com.exception;

public class Mytest1 

	public static void main(String[] args) 
		// TODO Auto-generated method stub
		System.out.println("第1步");
		System.out.println("第2步");
		try 
			System.out.println(5/0);
		 catch (Exception e) 
		e.printStackTrace();
		
        
		System.out.println("第3步");
		System.out.println("第4步");
	



第二个案例:

package com.exception;

import java.util.Scanner;

public class Mytest1 

	public static void main(String[] args) 
		// TODO Auto-generated method stub
		try 
			Scanner sc=new Scanner(System.in);
			System.out.println("请输入一个整数:");
			int num=sc.nextInt();
			System.out.println("您输入的数字是:"+num);
			
		 catch (Exception e) 
			//记录日志,进行提示等
			System.out.println("您输入的数据和接收的不一致");
			e.printStackTrace();
		
	




注释:inputmismatchexception是输入的不匹配异常。当然我们这里用的exception是所有异常的一个父类,它的范围是最大的,我们也可以把它改成对应的类型。

第三个案例:

package com.exception;

import java.util.InputMismatchException;
import java.util.Scanner;

public class Mytest1 

	public static void main(String[] args) 
		// TODO Auto-generated method stub
		try 
			Scanner sc=new Scanner(System.in);
			System.out.println("请输入第一个整数:");
			int num1=sc.nextInt();
			System.out.println("请输入第二个整数:");
			int num2=sc.nextInt();
			System.out.println("计算除法的结果是:"+(num1/num2));
			
		 catch (InputMismatchException e) 
			//记录日志,进行提示等
			System.out.println("您输入的数据不合法");
			e.printStackTrace();
		catch (ArithmeticException e) 
			System.out.println("输入的除数为0");
			e.printStackTrace();
		catch (Exception e) 
			System.out.println("出现了未知异常");
			e.printStackTrace();
		
	




总结:catch块可以有多个,但是范围小的一定要放在前面,范围大的一定要放在后面,并且在catch后我们还可以加入另外一个特殊的模块,我们叫它为finally,finally是什么意思呢?就是说不管你有没有出现异常,它总会执行finally的代码。

5.3 throw和throws及自定义异常

package com.exception;

import java.io.FileInputStream;
import java.io.FileNotFoundException;

public class Mytest2 
public static void readFile() throws ClassNotFoundException,FileNotFoundException
	Class.forName("com.exception.Mytest2");
	FileInputStream fis=new FileInputStream("C://file.txt");

	public static void main(String[] args) 
		// TODO Auto-generated method stub
        try 
			readFile();
		 catch (ClassNotFoundException e) 
			e.printStackTrace();
		 catch (FileNotFoundException e) 
			e.printStackTrace();
		
	



笔记:throws用在声明方法的时候,告诉别人该方法有可能出现的异常,我没有处理,你调用的时候来处理。

现在我们来看另外一个关键字throw,throw就是抛出一个具体的异常,下面我们来模拟一个场景:

package com.exception;

public class UserInfo 
private String name;
private int age;
public String getName() 
	return name;

public void setName(String name) 
	this.name = name;

public int getAge() 
	return age;

public void setAge(int age) throws Exception
	if (age<18||age>60) 
		//使用throw抛出异常
		throw new Exception("用户的年龄只能是18到60岁之间");
	
	this.age = age;


package com.exception;

public class Mytest3 

	public static void main(String[] args) 
		// TODO Auto-generated method stub
        UserInfo user=new UserInfo();
        user.setName("张三");
        try 
			user.setAge(1);
		 catch (Exception e) 
			// TODO Auto-generated catch block
			e.printStackTrace();
		
	




下面来讲自定义异常,以下是自定义异常的一个案例:

package com.exception;
//自定义的年龄不合理异常类
public class AgeErrorException extends Exception
public AgeErrorException(String message) 
	super(message);


package com.exception;

public class UserInfo 
private String name;
private int age;

	public String getName() 
	return name;


public void setName(String name) 
	this.name = name;


public int getAge() 
	return age;


public void setAge(int age) throws AgeErrorException
	if (age<18||age>60) 
		throw new AgeErrorException("用户的年龄只能是18到60岁之间");
	
	this.age = age;


	public static void main(String[] args) 
		// TODO Auto-generated method stub
        UserInfo user=new UserInfo();
        user.setName("张三");
        try 
			user.setAge(12);
		 catch (AgeErrorException e) 
			// TODO Auto-generated catch block
			e.printStackTrace();
		
	





总结:自定义异常是EXCEPTION异常的子类,所以必须要继承exception异常才行。

本章内容小节:throw和throws是另一种异常处理的方式,主要是将异常抛出由调用者来完成异常的处理,抛出异常一般和自定义异常配合的较多,以上就是关于Java异常处理的内容。

9.第五章文本处理三剑客之sed(代码片段)

第五部分sed1、删除centos7系统/etc/grub2.cfg文件中所有以空白开头的行行首的空白字符[root@centos8~]#sed-r‘s@^[[:space:]]+(.*)@1@‘2、删除/etc/fstab文件中所有以#开头,后边至少跟一个空白字符的行的行首的#和空白字符[root@centos8~]#sed-n‘/^[... 查看详情

阅读笔记《c程序员从校园到职场》第五章内存操作(代码片段)

参考:  让你提前认识软件开发(8):memset()与memcpy()函数 https://blog.csdn.net/zhouzxi/article/details/22478081让你提前认识软件开发(10):字符串处理函数及异常保护 https://blog.csdn.net/zhouzxi/article/details/22976307  查看详情

第五章小结(代码片段)

这一章我先来讲一下我实践第二题的思路先是基本结构体typedefstructintdoors;//门的数量int*p;//p指向具体门的编号,把p看作是一个整型数组node;再是主要函数intmain()node*a;inti,j,k,root;root=input(a);cout<<find(a,root)<<endl;return0;然后处... 查看详情

:异常处理(代码片段)

第五章:异常处理知识梳理本章内容分为:异常处理概述、try-catch处理异常、throw和throws、自定义异常。5.1异常处理概述问题:为什么要异常处理???编程中我们常说没有完美的代码,几乎每个应用... 查看详情

第五章标准i/o(代码片段)

5.1引言 本章说明标准I/O库。因为不仅在UNIX上,而且在很多操作系统上都实现了此库,所以它由ISOC标准说明。 标准I/O库处理很多细节,例如缓冲区分配,以优化长度执行I/O等。这些处理使用户不必担心如何选择使用正确... 查看详情

设计数据密集型应用第五章:复制(代码片段)

设计数据密集型应用第五章:复制与可能出错的东西比,'不可能’出错的东西最显著的特点就是:一旦真的出错,通常就彻底玩完了。——道格拉斯·亚当斯(1992)文章目录设计数据密集型应用第五章&... 查看详情

云计算第五章(代码片段)

Cloud-EnablingTechnology云使能技术BroadbandNetworksandInternetArchitecture宽带和Internet架构-Allcloudsmustbeconnectedtoanetwork(InternetorLAN)Thepotentialofcloudplatformsthereforegenerallygrowsinparallelwithadv 查看详情

第五章:变量(代码片段)

变量:int表示整数double表示带小数点的char表示单个字符string表示在存储字符串的变量bool表示判断真假usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;namespaceAnt1///<summary>// 查看详情

第五章小结(代码片段)

第五章学习了二叉树:每个结点至多只有两颗子树,且子树有左右之分。二叉树的遍历:几乎所有操作建立在遍历的基础上,利用递归完成二叉树前(根)序,中(根)序,后(根)序遍历。 voidPreOrderTraverse(BiTreeT)If(T)//若二... 查看详情

第五章(代码片段)

 认识模块什么是模块模块的导入和使用常用模块一collections模块时间模块random模块os模块sys模块序列化模块re模块  常见的场景:一个模块就是一个包含了python定义和声明的文件,文件名就是模块名字加上.py的后缀。&nb... 查看详情

第五章内容小结(代码片段)

在第五章,我们学习了树这个数据结构,并且学习了其定义、遍历等操作,最后还学习了哈夫曼树。一.树的遍历树的遍历操作有以下三种:1。先序遍历(根,左孩子,右孩子)voidPreOrderTravel(nodet[],intx)cout<<t[x].name<<"";if(... 查看详情

《算法》第五章部分程序part1(代码片段)

?书中第五章部分程序,包括在加上自己补充的代码,字母表类,字符串低位优先排序(桶排)●字母表类1packagepackage01;23importedu.princeton.cs.algs4.StdOut;45publicclassclass0167publicstaticfinalclass01BINARY=newclass01("01");89publicstaticfinalclass01 查看详情

solidity学习记录——第五章(代码片段)

...功能第三章编写DAPP所需的基础理论第四章完善僵尸功能第五章ERC721标准和加密资产文章目录Solidity学习记录前言一、本章主要目的二、学习过程1.本节课程知识点2.最终代码总结前言这应该是Solidity学习记录的最后一章,这五... 查看详情

python第五章函数(代码片段)

第五章函数5.1三元运算/三目运算v=前面if条件语句else后面#如果条件成立,"前面"赋值给v,否则后面赋值给v.v=aifa>belseb#取a和b中值较大的赋值给v#让用户输入值,如果值是整数,则转换成整数,否则赋值为Nonedata=input('请... 查看详情

节习题答案(第五章)(代码片段)

以下答案仅供参考,有错欢迎留言。Chapter5:TheRenderingPipeline1.Constructthevertexandindexlistofapyramid(金字塔),asshowninFigure5.35(即下图).Vertex  pyramid[5]=v0,v1,v2,v3,v4,v5;//注意要从面的out 查看详情

第五章装饰器进阶(代码片段)

1.对大批量函数添加装饰器,而且不定期的开关          #多个装饰器,添加批量管理的开关importtimeFLAG=Falsedefouter(flag):deftimer(f1):definner(*args,**kwargs):ifflag==True:start_time=time. 查看详情

机器学习实战第五章logistic回归(代码片段)

defgradAscent(dataMatIn,classLabels):dataMatrix=mat(dataMatIn)#converttoNumPymatrixlabelMat=mat(classLabels).transpose()#converttoNumPymatrixm,n=shape(dataMatrix)alpha=0.001maxCycles=500weights=ones(( 查看详情

《算法》第五章部分程序part2(代码片段)

?书中第五章部分程序,包括在加上自己补充的代码,字符串高位优先排序(计数+插排),(原地排序),(三路快排,与前面的三路归并排序相同)●计数+插排1packagepackage01;23importedu.princeton.cs.algs4.StdIn;4importedu.princeton.cs.algs4.St... 查看详情