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)
The program's execution comes to a halt right after the throw statement is executed. It then checks the closest try block to see if there is a catch statement that matches the type of exception. If a match is found, control is transferred to that catch statement. If no match is found, it moves on to the next enclosing try block and repeats the process. This continues until a matching catch is found or, if none is found, the default exception handler stops the program.
package DockerTpoint; public class Main { public static void main(String args[])throws InterruptedException{ Thread.sleep(1000); System.out.println("Hello DockerTpoint"); } }
Output:
Hello DockerTpoint
We handled the InterruptedException in the preceding program by using the throws keyword, and the output is Hello DockerTpoint.
Difference Between throw and throw in Java are mention below
Basis of Differences | throw | throws |
---|---|---|
Usage | Used to explicitly throw an exception | Used to declare that a method may throw an exception |
Syntax | throw <exception> |
'methodSignature throws <exception1>, <exception2>, ...' |
Placement | Inside a method body | In the method declaration |
Exception Type | Can throw any subclass of Throwable | Declares the checked exceptions that can be thrown |
Handling | Immediate handling required in catch blocks. | Exceptions can be handled by caller methods. |
Single/Multiple | Throws a single exception at a time | Can declare multiple exceptions using comma-separated list |
Checked/Unchecked | Can throw both checked and unchecked exceptions | Mainly used for checked exceptions |
Post your comment