Exception Handling Example Scenarios
Exception Handling Example Scenarios
to avoid this error we have to put the call to abc () method in try catch block; in
other words, handle the exception
class ThrowingException{
void abc()throws Exception{
System.out.println("this method can throw exception");
}
}
output: this method can throw exception
7. Try to Execute the Following code : (it throws the exception but does not declare that)
class MyException extends Exception{ }
////
class Game {
public int points;
Game(){
points=0;}
Game(int p){
points=p;}
}catch (MyException e) {
System.out.println("no points enough to use");
}
}
}
It will cause an error:
When a checked exception is thrown, it must be handled or that method should
declare it using throws keyword. In the given code, subtract method throws
ExcException but do not handle it, nor it declares the exception in method signature
using throws keyword. As we want to handle the exception in calling code, so we
should declare the method with throws clause instead of handling the subtract
method:
Correction:
void subtract(int pt)throws MyException { /* no change in method body */ }
Example 2:Below example illustrates finally block execution when exception occurs in try
block but doesnt get handled in catch block.
class Example2{
public static void main(String args[]){
try{
System.out.println("First statement of try block");
int num=45/0;
System.out.println(num);
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println("ArrayIndexOutOfBoundsException");
}
finally{
System.out.println("finally block");
}
System.out.println("Out of try-catch-finally block");
}
}
Output:
First statement of try block
finally block
Exception in thread "main" java.lang.ArithmeticException: / by zero
at beginnersbook.com.Example2.main(Details.java:6)
Example 3:Below example illustrates execution of finally, when exception occurs in try block
and handled in catch block.
class Example3{
public static void main(String args[]){
try{
System.out.println("First statement of try block");
int num=45/0;
System.out.println(num);
}
catch(ArithmeticException e){
System.out.println("ArithmeticException");
}
finally{
System.out.println("finally block");
}
System.out.println("Out of try-catch-finally block");
}
}
Output:
First statement of try block
ArithmeticException
finally block
Out of try-catch-finally block
}
catch(ArithmeticException ae)
{
System.out.println("Exception handled Inside myMethod!");
}
finally
{
System.out.println("finally block in myMethod!");
}
}
public static void main(String args[])
{
try
{
myMethod();
}
catch(ArrayIndexOutOfBoundsException indException){
System.out.println(indException.toString());
}
finally
{
System.out.println("finally block in main!");
}
System.out.println("Out of try-catch-finally block");
}
}
Output:
finally block in myMethod!
java.lang.ArrayIndexOutOfBoundsException: 7
finally block in main!
Out of try-catch-finally block