甲静块是代码使用静态关键字的块。通常,这些用于初始化静态成员。JVM在类加载时在main方法之前执行静态块。
public class MyClass { static{ System.out.println("Hello this is a static block"); } public static void main(String args[]){ System.out.println("This is main method"); } }
输出结果
Hello this is a static block This is main method
就像Java中的其他任何方法一样,当静态块中发生异常时,您也可以使用try-catch对来处理它。
import java.io.File; import java.util.Scanner; public class ThrowingExceptions{ static String path = "D://sample.txt"; static { try { Scanner sc = new Scanner(new File(path)); StringBuffer sb = new StringBuffer(); sb.append(sc.nextLine()); String data = sb.toString(); System.out.println(data); } catch(Exception ex) { System.out.println(""); } } public static void main(String args[]) { } }
输出结果
This is a sample fileThis is main method
每当抛出检查异常时,都需要在当前方法中对其进行处理,或者可以将其抛出(推迟)到调用方法中。
You cannot use throws keyword with a static block, and more over a static block is invoked at compile time (at the time of class loading) no method invokes it.
因此,如果在静态块中使用throw关键字引发异常,则必须将其包装在try-catch块中,否则会生成编译时错误。
import java.io.FileNotFoundException; public class ThrowingExceptions{ static String path = "D://sample.txt"; static { FileNotFoundException ex = new FileNotFoundException(); throw ex; } public static void main(String args[]) { } }
ThrowingExceptions.java:4: error: initializer must be able to complete normally static { ^ ThrowingExceptions.java:6: error: unreported exception FileNotFoundException; must be caught or declared to be thrown throw ex; ^ 2 errors