throws向上(方法调用处)声明抛出异常的类型
public class TestThrows {
public static void show() throws Exception {
}
public static void main(String [] args ){
//(1)try-catch-finally
try {
show ();
} catch (Exception e ) {
// TODO Auto-generated catch block
e .printStackTrace();
}
}
//(2) 继续向上抛出
public void fun() throws Exception{
show ();
}
}
如果一个方法的定义处使用throws 声明了Exception或Checked异常,要求方法的调用处必须做处理,处理方式有两种
(1)try-catch-finally
(2)继续向上(方法的调用处)抛出
如果一个方法的定义处使用throws声明了RuntimeException或RuntimeException的子类,方法的调用处可处理,也可不处理
public class TestThrows {
public static void show () throws RuntimeException {
}
public static void main(String [] args ){
show ();
}
public void fun() {
show ();
}
}
throw:写在方法的内部,用于抛出异常的对象
public class TestThrow {
public void show() throws Exception {
throw new Exception();
}
public void show1(){
try {
throw new Exception();
} catch (Exception e ) {
// TODO Auto-generated catch block
e .printStackTrace();
}
}
}
try-catch-finally
throw ,throws
throw的应用举例:
package com.wyq.study;
public class GenderExe extends Exception {
public GenderExe() {
super();
}
public GenderExe(String message) {
super(message);
System.out.println(message);
}
}
调用方法
package com.wyq.study;
import java.util.Scanner;
public class TestGend {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入性别:");
String gen = null;
try {
gen = sc.next();
if (!"男".equals(gen) && !"女".equals(gen)) {
throw new GenderExe("性别输入有误");
}
} catch (Exception e) {
System.err.println("程序进入到了异常信息中");
System.exit(0);
e.printStackTrace();
System.out.println(e.getMessage());
System.out.println(e.toString());
} finally {
System.out.println("程序结束。");
}
}
}
throw和throws的使用区别
package com.wyq.study;
import java.util.InputMismatchException;
import java.util.Scanner;
public class TestErr {
public static void main(String[] args) {
try {
fun();
} catch (Exception e1) {
try {
throw new Exception();
} catch (Exception e) {
e.printStackTrace();
}
// e1.printStackTrace();
}
int num1 = 0;
int num2 = 0;
int res = 0;
try {
Scanner sc = new Scanner(System.in);
System.out.println("请输入第一个数:");
num1 = sc.nextInt();
System.out.println("请输入第二个数:");
num2 = sc.nextInt();
res = num1 / num2;
} catch (Exception e) {
System.exit(1);
System.out.println("类型有误");
// System.out.println("~~~~~~~~~~~~~e.printStackTrace()~~~~~~~~~~~~~~~~");
// e.printStackTrace();
// System.err.println("++++++++++++++e.getMessage()+++++++++++++++++");
// System.out.println(e.getMessage());
System.out.println("**************e.toString()*******************");
System.err.println(e.toString());
} finally {
System.out.println("结束!");
}
System.out.println(num1 + "\t" + num2 + "=" + res);
}
public static void fun() throws Exception{
throw new Exception();
}
}