1. Throw an exception: Let the code that calls this method go to the Tube
public static void GetFile () throws exception{}
Package Com.throwable;import Java.io.bufferedreader;import Java.io.file;import java.io.fileinputstream;import Java.io.filenotfoundexception;import Java.io.inputstreamreader;public class Excetiondemo {/** * @param args * @throws Exception */public static voidMain (STring[] args) {//TODO auto-generated method stubtry {GetFile ();}Catch(Exception e) {//TODO auto-generated catch Blocke.printstacktrace ();} }Public static void GetFile () throws Exception{File File = new file ("C:\\test.java"); FileInputStream fis = new FileInputStream (file); BufferedReader br = new BufferedReader (new InputStreamReader (FIS)); Unhandled exception type FileNotFoundException//2 quick fixed available:add throwable; Surrownd try/catch String line = Br.readline (); System.out.println (line); Output result: Heheheheh}}
2. Around the code block that is currently going to appear the exception, try--catch
Package Com.throwable;import Java.io.bufferedreader;import Java.io.file;import java.io.fileinputstream;import Java.io.filenotfoundexception;import Java.io.ioexception;import Java.io.inputstreamreader;public Class ExcetionDemo2 {/** * @param args * @throws Exception */public static void Main (string[] args) {//TODO auto-generated met Hod stubgetfile ();} public static void GetFile () {File File = new file ("C:\\test.java"); FileInputStream fis;try {FIS = newfileinputstream (file);BufferedReader br = new BufferedReader (new InputStreamReader (FIS)); Unhandled exception type FILENOTFOUNDEXCEPTION//2 quick fixed available:add throwable; Surrownd try/catch String line;line =br.readline ();System.out.println (line); Output result: Heheheheh}catch (Exception e) {TODO auto-generated catch Blocke.printstacktrace ();} }}
Two ways to catch exceptions exception