java:异常机制(try,catch,finally,throw,throws,自定义异常)
* String类中的格式化字符串的方法:
* public static String format(String format, Object... args):使用指定的格式字符串和参数返回一个格式化字符串。
*
* 当输入内容非整数时,将出现java.util.InputMismatchException异常(输入不匹配异常)
* 当除数为零时,出现java.lang.ArithmeticException异常。(算数异常)
* 传统的解决方案:利用if进行判断来堵漏洞(麻烦)
* 异常:程序在执行过程中遇到特殊的事件,导致程序中断执行。
* java中的异常处理: try,catch,finally,throws,throw
* 1.try...catch
* try{
* //可能出现异常的代码
* }catch(异常类型 e){
* //处理异常的代码
* }
* 执行过程:当try中代码出现异常时,将会抛出一个异常对象,
* 该异常对象会和catch中异常类型进行匹配,如果匹配成功将执行catch中的代码,否则程序中断执行。
* 异常对象中常用的方法
* printStackTrace():打印异常堆栈跟踪信息(类,消息和异常跟踪信息)
* toString():异常信息(类和消息)
* getMessage():异常消息(异常消息)
public class TestException {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("请输入被除数:");
int num1=;
int num2=;
int num3=;
try{
num1 = input.nextInt();
System.out.println("请输入除数:");
num2 = input.nextInt();
num3 = num1/num2;
}catch(Exception e){ //(InputMismatchException e)
// System.err.println("代码出错了...");
// e.printStackTrace();//打印异常堆栈跟踪信息(常用)
// System.err.println(e.toString());//toString()异常信息
System.err.println(e.getMessage());//getMessage()获取异常消息
}
String str = String.format("%d/%d=%d", num1,num2,num3);
System.out.println(str);
System.out.println("程序执行结束!");
}
}
/**
* try...catch结构:
* 语法:
* try{
* //可能出现异常的代码
* }catch(异常类型1 e){
* //处理异常类型1的代码;
* }catch(异常类型2 e){
* //处理异常类型2的代码;
* }...
* 执行过程与多重的if...else if条件分支类似,如果try中的代码发生的异常,将抛出一个异常对象,
* 该异常对象会catch中的异常类型挨个进行匹配,如果匹配成功将执行catch块中的处理代码。
* 注意:异常类型的范围应该是有小到大,否则会导致其下的catch中的代码不会执行。
*/
public class TestException3 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("请输入被除数:");
int num1=;
int num2=;
int num3=;
try{
num1 = input.nextInt();
System.out.println("请输入除数:");
num2 = input.nextInt();
num3 = num1/num2;
}catch(InputMismatchException e){
System.err.println("请输入数字!");
}catch(ArithmeticException e){
System.err.println("除数不能为零!");
}
String str = String.format("%d/%d=%d", num1,num2,num3);
System.out.println(str);
System.out.println("程序执行结束!");
}
}
* try...catch...finally
* finally中的代码不论异常是否发生,永远都会执行(除非使用System.exit()退出JVM)。
* 经常将资源释放(IO流,数据库连接等)的代码放在finally中,确保资源能得到释放
* try...catch 正确
* try....catch...finally 正确
* try....finally 正确
* catch..finally 错误
public class TryCatchFinally2 {
public static void main(String[] args) {
try{
System.out.println("try.....");
int num = /;
// return;
System.exit();//退出应用程序,退出JVM
}catch(Exception e){
System.out.println("catch....");
}finally{
System.out.println("finally....");
}
}
}
异常有哪些:
算术异常类:ArithmeticExecption
空指针异常类:NullPointerException
类型强制转换异常:ClassCastException
数组负下标异常:NegativeArrayException
数组下标越界异常:ArrayIndexOutOfBoundsException
违背安全原则异常:SecturityException
文件已结束异常:EOFException
文件未找到异常:FileNotFoundException
字符串转换为数字异常:NumberFormatException
操作数据库异常:SQLException
输入输出异常:IOException
方法未找到异常:NoSuchMethodException
* throws和throw关键字. (注意:声明异常后,内部没有try,catch,throw也不会报错)
* throws:在声明方法时声明该方法存在的异常。
* throw:在方法内部抛出异常。
* throws和throw的区别:
* 1.位置不同: throws在方法声明名用于声明该方法存在的异常,throw在方法内部用于抛出异常。
* 2.类型不同: throws后边跟的是异常类型,throw后边的异常对象
* 3.作用不同: throws的作用是告知方法的调用者该方法存在某种异常类型需要处理,
* throw的作用在用于抛出某种具体的异常对象。
* 经常throws和throw结合使用。
public class TestThrows {
public static int divide() throws ArithmeticException{
Scanner input = new Scanner(System.in);
System.out.println("请输出被除数:");
int num1 = input.nextInt();
System.out.println("请输出除数:");
int num2 = input.nextInt();
int num3 =;
try{
num3 =num1/num2;
}catch(ArithmeticException e){
throw new ArithmeticException();//相等于抛出一个异常对象
}
return num3;
}
public static void main(String[] args) {
try{
int num3 = divide();
}catch(ArithmeticException e){
System.err.println("除数不能为零!");
}
}
}
*检查异常必须进行处理,否则无法通过编译。
*常见的检查异常:
*ClassNotFoundException:类找不到异常。
*SQLException:操作SQL语句出现的异常信息
*IOException:操作IO流出现的异常信息
*....
*捕获检查异常的快捷键:1.选中出现检查异常的代码
* 2.alt+shift+z
public class TestCheckedException {
public static void main(String[] args) {
try {
Class.forName("java.lang.String");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
自定义异常:
* 自定义异常:如果JDK中异常类型无法满足程序需要。
* 步骤:
* 1.编写自定义异常类:继承Exception或RuntimeException
* 2.编写构造方法,继承父类的实现
* 3.实例化自定义异常对象
* 4.使用throw抛出
public class AgeException extends RuntimeException{
public AgeException(String message){
super(message);
}
}
public class Agezz {
private int age;
private int score;
public int getAge() {
return age;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
public Agezz() {
super();
// TODO Auto-generated constructor stub
}
public Agezz(int age, int score) {
super();
this.age = age;
this.score = score;
}
public void setAge(int age)throws AgeException{
if(age>&&age<){
this.age=age;
}else{
throw new AgeException("不符合年龄");
}
}
@Override
public String toString() {
return "Agezz [age=" + age + ", score=" + score + "]";
}
}
public class Agetest {
public static void main(String[] args) {
Agezz a=new Agezz(,);
try{
a.setAge();
}catch(AgeException e){
System.out.println(e.getMessage());
}finally{
System.out.println("设置完成");
}
System.out.println(a);
}
}
java:异常机制(try,catch,finally,throw,throws,自定义异常)的更多相关文章
- Java异常机制关键字总结,及throws 和 throw 的区别
在Java的异常机制中,时常出现五个关键字:try , catch , throw , throws , finally. 下面将总结各个关键字的用法,以及throw和throws的区别: (1) t ...
- 全面理解java异常机制
在理想状态下,程序会按照我们预想的步骤一步一步的执行,但是即使你是大V,你也不可避免出错,所以java为我们提供了异常机制.本文将会从以下几个方面介绍java中的异常机制: 异常机制的层次结构 异常的 ...
- Java 异常机制
Java 异常机制 什么是异常 异常指不期而至的各种状况,如:文件找不到.网络连接失败.非法参数等.异常是一个事件,它发生在程序运行期间,干扰了正常的指令流程 为什么要有异常 什么出错了 哪里出错了 ...
- 【55】java异常机制剖析
一.为什么要使用异常 首先我们可以明确一点就是异常的处理机制可以确保我们程序的健壮性,提高系统可用率.虽然我们不是特别喜欢看到它,但是我们不能不承认它的地位,作用.有异常就说明程序存在问题,有助于我们 ...
- Java异常机制及异常处理建议
1.Java异常机制 异常指不期而至的各种状况,如:文件找不到.网络连接失败.非法参数等.异常是一个事件,它发生在程序运行期间,干扰了正常的指令流程.Java通过API中Throwable类的众多子类 ...
- [Java学习笔记] Java异常机制(也许是全网最独特视角)
Java 异常机制(也许是全网最独特视角) 一.Java中的"异常"指什么 什么是异常 一句话简单理解:异常是程序运行中的一些异常或者错误. (纯字面意思) Error类 和 Ex ...
- 基础知识《十》java 异常捕捉 ( try catch finally ) 你真的掌握了吗?
本文转载自 java 异常捕捉 ( try catch finally ) 你真的掌握了吗? 前言:java 中的异常处理机制你真的理解了吗?掌握了吗?catch 体里遇到 return 是怎么处理 ...
- 顺平讲try catch finally throw throws(精华)
try catch finally 有点像if else语句 还有像javascript的服务器执行成功后的回调函数,success:function(){ 进行处理 }; throws的意思是将异 ...
- Java基础-异常处理机制 及异常处理的五个关键字:try/catch/finally/throw /throws
笔记: /** 异常处理机制: 抓抛模型 * 1."抛", 一旦抛出,程序终止! printStackTrace()显示异常路径! * 2."抓", 抓住异常 ...
随机推荐
- 【AGC006 C】Rabbit Exercise
题意 有 \(n\) 只兔子在数轴上,第 \(i\) 只兔子的初始坐标为整数 \(x_i\). 现在这些兔子会按照下面的规则做体操.每一轮体操都由 \(m\) 次跳跃组成:在第 \(j\) 次跳跃时, ...
- CH5102/SPOJ?? Mobile Service/P4046 [JSOI2010]快递服务[线性dp+卡常]
http://contest-hunter.org:83/contest/0x50%E3%80%8C%E5%8A%A8%E6%80%81%E8%A7%84%E5%88%92%E3%80%8D%E4%B ...
- PHP开启错误提示而不是单单返回500
方法一 修改php.ini文件和php-fpm.conf php.ini文件在我使用的发行版本/etc/php/<版本号>/cli/php.ini php-fpm.conf文件在/etc/ ...
- (转载)搜索引擎的Query自动纠错技术和架构详解
from http://www.52nlp.cn/%E8%BE%BE%E8%A7%82%E6%95%B0%E6%8D%AE%E6%90%9C%E7%B4%A2%E5%BC%95%E6%93%8E%E7 ...
- 【leetcode】1268. Search Suggestions System
题目如下: Given an array of strings products and a string searchWord. We want to design a system that su ...
- python 正则表达式实例:
#!/usr/bin/python import re line = "Cats are smarter than dogs" matchObj = re.match( r'(.* ...
- 文件选择对话框:CFileDialog
程序如下: CString FilePathName; //文件名参数定义 CFileDialog Dlg(TRUE,NULL,NULL, ...
- python类装饰器即__call__方法
上一篇中我对学习过程中的装饰器进行了总结和整理,这一节简单整理下类装饰器 1.类中的__call__方法: 我们在定义好一个类后,实例化出一个对象,如果对这个对象以直接在后边加括号的方式进行调用,程序 ...
- Makefile样例
Makefile1 src = $(wildcard ./*cpp) obj = $(patsubst %.cpp, %.o,$(src)) target = test $(target) : $(o ...
- [pytorch笔记] torch.nn vs torch.nn.functional; model.eval() vs torch.no_grad(); nn.Sequential() vs nn.moduleList
1. torch.nn与torch.nn.functional之间的区别和联系 https://blog.csdn.net/GZHermit/article/details/78730856 nn和n ...