初学Exceptions

异常的第一种用法是Java比C++增加的一种使用方法,但是其抛出异常的方法一般只有直接抛出到method体之外,不能用try catch(原因不明确,可能是因为try catch l里的variables都只能在curly brakets 里使用);如果要将读入文件单独成为一个method的话,抛出的异常需要两次,先抛出到mathod之外,再抛出到main之外。
package myexception;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class Test2 {
public static void main(String[] args) throws FileNotFoundException {

    String fileName = new String("hello.txt");

    File textFile = new File(fileName);

    throwEx(textFile);

}

public static void throwEx(File file) throws FileNotFoundException  {
    Scanner in = new Scanner(file);
    int a = in.nextInt();
    System.out.println(a);

    while (in.hasNext()) {
        System.out.println(in.next());
    }

    in.close();

}

}

抛出异常的传统作用是继承C++的,是终止进程的方法,在不同的Java文件中的异常最终都要在main里再次抛出

import java.io.IOException;
import java.util.Scanner;

public class App {

public static void main(String[] args) {
    Test test = new Test();
    Scanner in = new Scanner(System.in);
    try {
        test.run(in.nextBoolean());
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

}

/
import java.io.IOException;

public class Test {
public void run(boolean a) throws IOException {
/// a is false means this field is wrong , the method need to be
/// terminated by FIleException
if (a)
throw new FIleException(“a is true”);
/// a is false means this field is wrong , the method need to be
/// terminated by IOException
if (!a)
throw new IOException();
/// a is false means this field is wrong , the method need to be
/// terminated by FIleException
if (a)
throw new FIleException(“a is true”);
}

}
///
import java.io.IOException;

public class FIleException extends IOException {

public FIleException(String message) {
    super(message);

}

}

可以在一个method里抛出多个异常,则此时再main里抛出异常会有三种方法;如果要抛出子类和父类的异常则只需要抛出父类的异常即可,这是因为多态的性质(多态,其实是一种downcasting,而upcasting则是危险的)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值