2017-03-15 22 views
0

我想了解scala中的錯誤處理。Scalac編譯器不會創建一個.class文件

我編譯的代碼如下

scalac sampleExceptionHandling.sc

我認爲這將創建一個.class文件,並使用javap的命令,我可以看一下相應的Java代碼。因爲某些原因,.class文件沒有被創建。執行Scalac命令後也不會出現任何錯誤。

有什麼建議嗎?

import java.io.FileReader 
import java.io.FileNotFoundException 
import java.io.IOException 

object Demo { 
    def main(args: Array[String]) { 
    try { 
    val f = new FileReader("input.txt") 
    } catch { 
    case ex: FileNotFoundException =>{ 
     println("Missing file exception") 
    } 

    case ex: IOException => { 
     println("IO Exception") 
    } 
    } 
    } 
} 
+0

對不起。在我使用Scalac之後,它創建了名爲「Demo」(Demo.class)的類名。但我如何從命令提示符運行該程序? – jason

+0

看到答案。你將不得不做'scala Demo'。 – prayagupd

回答

4

它確實創建了.class,它與您的類名相同,而不是您的文件名。

以下是scalac sampleExceptionHandling.sc

$ ll 
total 24 
10909194 -rw-r--r-- 1 as18 prayagupd 936 Mar 15 10:00 Demo$.class 
10909193 -rw-r--r-- 1 as18 prayagupd 565 Mar 15 10:00 Demo.class 
10909167 -rw-r--r-- 1 as18 prayagupd 378 Mar 15 09:59 sampleExceptionHandling.sc 

結果要運行的類

$ scala Demo 
Missing file exception 

要查看字節碼,

$ javap -c Demo.class 
Compiled from "sampleExceptionHandling.sc" 
public final class Demo { 
    public static void main(java.lang.String[]); 
    Code: 
     0: getstatic  #16     // Field Demo$.MODULE$:LDemo$; 
     3: aload_0 
     4: invokevirtual #18     // Method Demo$.main:([Ljava/lang/String;)V 
     7: return 
} 

而且,

$ javap -c Demo$.class 
Compiled from "sampleExceptionHandling.sc" 
public final class Demo$ { 
    public static final Demo$ MODULE$; 

    public static {}; 
    Code: 
     0: new   #2     // class Demo$ 
     3: invokespecial #12     // Method "<init>":()V 
     6: return 

    public void main(java.lang.String[]); 
    Code: 
     0: new   #20     // class java/io/FileReader 
     3: dup 
     4: ldc   #22     // String input.txt 
     6: invokespecial #25     // Method java/io/FileReader."<init>":(Ljava/lang/String;)V 
     9: astore  4 
     11: goto   35 
     14: astore_2 
     15: getstatic  #30     // Field scala/Predef$.MODULE$:Lscala/Predef$; 
     18: ldc   #32     // String IO Exception 
     20: invokevirtual #36     // Method scala/Predef$.println:(Ljava/lang/Object;)V 
     23: goto   35 
     26: astore_3 
     27: getstatic  #30     // Field scala/Predef$.MODULE$:Lscala/Predef$; 
     30: ldc   #38     // String Missing file exception 
     32: invokevirtual #36     // Method scala/Predef$.println:(Ljava/lang/Object;)V 
     35: return 
    Exception table: 
     from to target type 
      0 14 26 Class java/io/FileNotFoundException 
      0 14 14 Class java/io/IOException 
} 
相關問題