使用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(); } }
catch语句涉及声明您尝试捕获的异常类型。如果try块中发生异常,则检查try后面的catch块(或块)。如果发生的异常类型在catch块中列出,则异常将传递给catch块,就像参数传递给方法参数一样。示例import java.io.File; import java.io.FileInputStream; public class Test { public static void main(String args[]) { System.out.println("Hello"); try { File file = new File("my_file"); ... 阅读更多
当您将格式不正确的字符串变量转换为与其不兼容的整数(数字格式)时,就会发生此异常。示例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)