newzad
newzad

Reputation: 706

Throw an intentional exception to stop program executing in Java

I put an exception intentionally to stop program executing but it seems that the executions continues after the exception is thrown.

try{
   System.out.println("Executing ");
   throw new RuntimeException("This is thrown intentionally");
} catch {....
}
System.out.println("Must not execute");

I don't want to use System.exit() since I don't want to stop JVM and don't want to use return since I want it look like an error happened. Please help to on this.

Upvotes: 3

Views: 5647

Answers (1)

Debojit Saikia
Debojit Saikia

Reputation: 10632

You don't need to catch the exception after it is thrown. If you catch it there, the program will start executing the statements that are there after the catch block.

System.out.println("Executing ");
if(1 == 1) // I put this 'if' here so that the code compiles
{
     throw new RuntimeException("This is thrown intentionally");
}
System.out.println("Must not execute");

Upvotes: 2

Related Questions