2015-01-07 59 views
4

当我们有一个自定义例外,比如SkillRequiredException,我们检查一些条件,比如检查员工的技能,如果条件失败,我们会抛出SkillRequiredException。直到这我很好,清楚。如何将Exceptional对象转换为Java checked Exception之一?

但是让FileInputStream类。它抛出FileNotFound检查异常。当我看到FileInputStream源代码时,我看不到任何地方 - 检查某些条件(和)throw FileNotFoundException

我的问题是,JVM如何知道该文件不存在以及由JVM创建的Exceptional Object如何识别为FileNotFoundException而不使用throw FileNotFoundExceptionFileInputStream类中?

回答

7

好吧,如果你检查哪些方法是由FileInputStream构造函数调用时,你会看到,它最终调用:

private native void open(String name) throws FileNotFoundException; 

这是一个本地方法,这意味着它不是用Java编写的,你不能看到它的代码,但它仍然可以抛出一个FileNotFoundException异常。

+0

我现在能理解叶兰。谢谢 – Sanjeevan

0

在的FileInputStream你会发现这样的代码:

public FileInputStream(File file) throws FileNotFoundException { 
     ... 
     open(name); 
} 

和开放的定义:

/* 
* Opens the specified file for reading. 
* @param name the name of the file 
*/ 
private native void open(String name) throws FileNotFoundException; 

你可以很容易地检查你的JDK如何使用JNI根据您的操作系统来执行此操作, Windows使用OpenJdk的例子,你可以在io_util_md.c中找到这段代码(complete source):

if (h == INVALID_HANDLE_VALUE) { 
    int error = GetLastError(); 
    if (error == ERROR_TOO_MANY_OPEN_FILES) { 
     JNU_ThrowByName(env, JNU_JAVAIOPKG "IOException", 
         "Too many open files"); 
     return -1; 
    } 
    throwFileNotFoundException(env, path); 
    return -1; 
} 

你可以检查throwFileNotFoundException的io_util.c(complete code)执行:

void 
throwFileNotFoundException(JNIEnv *env, jstring path) 
{ 
    char buf[256]; 
    jint n; 
    jobject x; 
    jstring why = NULL; 

    n = JVM_GetLastErrorString(buf, sizeof(buf)); 
    if (n > 0) { 
     why = JNU_NewStringPlatform(env, buf); 
    } 
    x = JNU_NewObjectByName(env, 
          "java/io/FileNotFoundException", 
          "(Ljava/lang/String;Ljava/lang/String;)V", 
          path, why); 
    if (x != NULL) { 
     (*env)->Throw(env, x); 
    } 
} 
+0

非常感谢帕特里克的解释 – Sanjeevan