throw Instance
Example: throw new ArithmeticException("/ by zero");
public class Main { void fun(){ try { System.out.println("fun() method "); throw new NullPointerException(); } catch (NullPointerException e){ throw e; } } public static void main(String args[]){ try{ Main main=new Main(); main.fun(); } catch(NullPointerException e){ System.out.println("Caught in the main method"); } } }
Output:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Unhandled exception type InterruptedException
at HELLO/DockerTpoint.Main.main(Main.java:5)
Java Exception Handling involves the interruption of program execution when a throw statement is executed. Subsequently, the closest try block is examined to determine if it contains a corresponding catch statement for the specific type of exception. If a match is found, control is transferred to that particular statement. However, if no matching catch is discovered, the program will be halted by the default exception handler. This mechanism ensures effective management of exceptions in Java programming.
class userException extends Exception { public userException(String str) { super(str); } } public class Main { public static void main(String args[]){ try{ throw new userException("User defined exception"); } catch (userException userexception){ System.out.println("Exception Caught"); System.out.println(userexception.getMessage()); } } }
Output:
Exception Caught
User defined exception
Post your comment