Sample program:
Public class testthrows { publicstaticvoid main (string[] args) { new FileInputStream ("a.txt"); } }
Why does the above program fully conform to the Java syntax specification, but it will error?
Correction:
public class Testthrows{public static void Main (string[] args) throws Filenotfoundexception{fileinputstream fis = New
fileinputstream ("A.txt");}}
throwsstatement indicates that there may be some (or more) differentoften, but it cannot handle these exceptions by itself, but requires the caller toprocessing. when a method containsthrowsclause, you need to call this method in theused in codetry/catch/finallyTo capture, or to re-it is declared, otherwise the compile times are wrong.
Controlled and uncontrolled exceptionsthrowsthe exception declared in the statement is called controlled (checked) The differentOften directly derived from theExceptionclass. runtimeexception(its base class isException)and theError(the base class isThrowable) is called a non-controlled exception. This exceptionnot inthrowsdeclaration in a statement. Checkedexceptiondemo.javaThis example shows the two differentthe usual characteristics. Methods to throw multiple controlled exceptionsA method can declare multiple exceptions to be thrownint g (float h) throws Oneexception,twoexception{...}For example:
ImportJava.io.*; Public classThrowmultiexceptionsdemo { Public Static voidMain (string[] args) {Try{throwstest (); } Catch(IOException e) {System.out.println ("Catch Exception"); } } Private Static voidThrowstest ()throwsarithmeticexception,ioexception {System.out.println ("It's just a test."); //The program process assumes that an exception occurred Throw NewIOException (); //throw new ArithmeticException (); } }
Results:
Note aJavaone of the more unique areas of exception handling:When a method declares a flat throw of more than one exception, the code can be compiled successfully as soon as any of the exceptions are catch in the method call statement. The subclass throws the limit of the controlled exception:a subclass ofthrowsclause throws an exception that cannot be the parent of an exception object that is thrown by a method with the same name as its base class.
Import java.io.*;p ublic class overridethrows{public void Test () throws Ioexception{fileinputstream FIS = new FileInputStream ("A.txt");}} Class Sub extends overridethrows{//if the test method declaration throws a larger exception than the parent class method, such as Exception //The code will not compile ... public void test () throws filenotfoundexception{ //...}}
Java 7and later versions, allowed in aCatchmultiple exceptions are captured in a block. For example:
Try { //... Throw New socketexception (); } Catch (SocketException | SecurityException | nullpointerexception e) { //exception handler }
Java exception handling "controlled (checked)" exception