Java内置异常
Ioxception 是非RunTimeException
字符串转换为数字异常类:
23u是没办法这样转化为数字的
我们来修改一下
try-catch(finally)语句捕获异常
注意点:
- catch要和try一起使用,不能单独使用;
- catch块的排列顺序是从特殊到一般;
- 一旦某一个catch块被执行,其他catch块都会被忽略;
- try -catch可以嵌套使用。
throw和throws
看一个throw例子
import java.util.InputMismatchException;
import java.util.Scanner;
class demo {
public static void check(){
Scanner sc=new Scanner(System.in);
System.out.println("please enter the number of the products");
int num=sc.nextInt();
if (num<0){
throw new NumberFormatException("the nunber can't below zero");
//注意这里的throw的用法
//括号里放异常原因
}
else{
System.out.println("the num:"+num);
}
}
public static void main(String[] args) {
try {
check();
} catch(InputMismatchException e2){
System.out.println(e2.toString());
} catch (Exception e) {
//Exception e=new NumberFormatException("the nunber can't below zero")
System.out.println(e.getMessage());
}
}
}
捕获异常的三种方法:
- e.toString();
获得异常的种类和错误信息e.getmessage()。
2.e.getMessage();
获得错误信息。
3.e.printStackTrace();
打印异常种类,错误信息和出错位置
throws的例子
import java.util.InputMismatchException;
import java.util.Scanner;
class demo {
public static void check() throws NumberFormatException
//throws放在方法参数列表之后
//throws后面可以有多个,用逗号隔开就行
{
Scanner sc=new Scanner(System.in);
System.out.println("please enter the number of the products");
int num=sc.nextInt();
if (num<0){
throw new NumberFormatException("the nunber can't below zero");
}
else{
System.out.println("the num:"+num);
}
}
public static void main(String[] args) {
try {
check();
} catch(InputMismatchException e2){
System.out.println(e2.toString());
} catch (Exception e) {
System.out.println(e.getMessage());
}
总结throws和throw的区别:
1.throw在方法内部;
throws在方法参数列表后面;
2.throw一次一个
throws可以一次多个
自定义异常类
例题代码如下
import java.util.InputMismatchException;
import java.util.Scanner;
class myexception extends Exception{
String mystring;
public myexception(String mystring){
this.mystring=mystring;
}
@Override
public String toString(){
// Overridden the methods of the parent class
return mystring;
}
}
class demo {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("please enter the number of the products");
int num = sc.nextInt();
try {
if (num < 0) {
throw new myexception("the nunber can't below zero");
} else {
System.out.println("the num:" + num);
}
} catch (myexception myexception) {
myexception.printStackTrace();
}
}}
结果:
区分概念
1.编译异常:语法错误;
2.运行时异常:逻辑错误。