throw:
表示也是抛出异常,抛出的一个异常对象 (throw new 异常类名() :匿名对象的方式)
面试题:
throws和throw的区别?throws:也是表示抛出异常,它后面跟的异常类名,并且可以多个异常类名中间逗号开
举例:
public void show() throws IoException,ClassNotFoundException{...}
在方法上抛出,由调用者处理
它表示抛出异常的可能性
throw:抛出的一个异常对象
在语句体中抛出的,由语句体进行处理
它表示抛出异常的肯定性
public class ExceptionDemo {
public static void main(String[] args) {
// method() ;
//调用者必须处理
try {
method2();
} catch (Exception e) {
e.printStackTrace();
}
}
private static void method2() throws Exception {
int a = 10 ;
int b = 0 ;
if(b==0) {
throw new Exception();
}else {
System.out.println(a/b);
}
}
private static void method() {
int a = 10 ;
int b = 0 ;
if(b==0) {
throw new ArithmeticException(); //throw 后面跟的是一个异常对象 匿名对象的方式
}else {
System.out.println(a/b);
}
}
}
try...catch...finally
finally语句体是一定会执行的,除非是Jvm退出了面试题:
如果catch里面有return 语句,finally中的代码还会执行,是在return语句之前执行还是return后执行?
finally中代码是一定会执行的,是在return前
public class FinallyDemo {
public static void main(String[] args) {
System.out.println(getInt());
}
private static int getInt() {
int a ;
try {
a = 10 ;
System.out.println(a/0);
a = 20 ;
}catch(Exception e) {
a= 30 ;
return a ;
/**
* try的代码出现问题了,执行catch中的语句,30赋值a,
* return 30(已经形成了一个回路径)finally代码一定会执行(除非Jvm) a = 40 ,在fianlly外面
* 有return a: a记录回路径的那个a,返回30
* 如果finally里面有return a;则返回40
*/
}finally {
//除非jvm退出了
a = 40 ;
}
return a;//30
}
}
异常中的注意事项:
子类继承父类的时候的注意事项1)子类重写父类的方法的时候,子类的方法的抛出的异常必须要么是父类的方法异常一样,要么是父类方法异常的子类
2)子类重写父类方法的时候,如果父类中的这个方法没有抛出异常,那么子类重写的这个方法也不能抛出异常,只能try...catch
public class ExceptionTest {
}
class Fu{
public void show() throws Exception {
}
public void method() {
}
}
class Zi extends Fu{
@Override
public void show() throws ArithmeticException{
}
@Override
public void method(){
try {
String str = "2018-5-13" ;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd") ;
Date d =sdf.parse(str) ;
System.out.println(d);
} catch (Exception e) {
e.printStackTrace();
}
}
}