在使用 FileInputStream、FileOutputStream 和 RandomAccessFile 类时,我们需要将文件的路径传递给它们的构造函数。如果指定路径中的文件不存在,则会引发 FileNotFoundException 异常。示例public class Sample { public static void main(String args[]) throws Exception { File file = new File("myFile"); FileInputStream fis = new FileInputStream(file); System.out.println("Hello"); } }输出Exception in thread "main" java.io.FileNotFoundException: myFile (The system cannot find the file specified) at java.io.FileInputStream.open(Native Method) at java.io.FileInputStream.open(Unknown Source) at java.io.FileInputStream.(Unknown Source) ... 阅读更多
throw 关键字用于显式地抛出异常。示例public class Test { public static void main(String[] args) { throw new NullPointerException(); } }Exception in thread "main" java.lang.NullPointerException at a6.dateAndTime.Test.main(Test.java:5)throws 关键字在 Java 中用于推迟检查异常的处理。public class Test { public static void main(String[] args)throws NullPointerException { throw new NullPointerException(); } }
当您将字符串变量转换为不兼容的数字格式(整数格式)时,就会发生此异常。示例public class Test { public static void main(String[] args) { int data = Integer.parseInt("hello"); } }输出Exception in thread "main" java.lang.NumberFormatException: For input string: "hello" at java.lang.NumberFormatException.forInputString(Unknown Source) at java.lang.Integer.parseInt(Unknown Source) at java.lang.Integer.parseInt(Unknown Source) at a6.dateAndTime.Test.main(Test.java:5)