The try statement allows you to define a block of code to be tested for errors while it is being executed. The catch statement allows you to define a block of code to be executed if an error occurs in the try block.
Example 1:
Java
import java.io.File;import java.io.FileInputStream;public class TryCatchException {public static void main(String[] args) {String pathname = "file";File file = new File(pathname);@SuppressWarnings("unused")FileInputStream fileInputStream = null;try {fileInputStream = new FileInputStream(file);} catch (Exception e) {System.out.println("File Not Present in the system");}}}
Output
File Not Present in the system
Example 2:
Java
import java.io.*;class M {void method() throws IOException {throw new IOException("error");}}public class Demothrows {public static void main(String args[]) {try {M m = new M();m.method();} catch (Exception e) {System.out.println("exception handled");}System.out.println("normal flow...");}}
Output
exception handled normal flow...
Exception Handling Using Throw keyword
Exception Handling Using Throws keyword
Java catch Multiple Exceptions
Java try/ catch block exception handling
Java nested try block exception handling
Java custom exception handling
Java finally block exception handling
Exception Handling Interview Questions
No comments:
Post a Comment