0% found this document useful (0 votes)
168 views

Exception Handling Example Scenarios

1. The document provides examples of try-catch blocks in Java to handle exceptions. It demonstrates how to catch specific exceptions like ArithmeticException and ArrayIndexOutOfBoundsException. Finally blocks are also shown which execute regardless of whether an exception occurs or not. 2. User-defined exceptions are demonstrated by creating a custom exception class that extends the Exception class. Methods can declare exceptions using the throws keyword to indicate the method may throw that exception. 3. Exceptions can be caught in calling methods to handle exceptions thrown in other methods. This allows exceptions to be handled at an appropriate level without needing to handle them where they occur.

Uploaded by

Haseeb Chughtai
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
168 views

Exception Handling Example Scenarios

1. The document provides examples of try-catch blocks in Java to handle exceptions. It demonstrates how to catch specific exceptions like ArithmeticException and ArrayIndexOutOfBoundsException. Finally blocks are also shown which execute regardless of whether an exception occurs or not. 2. User-defined exceptions are demonstrated by creating a custom exception class that extends the Exception class. Methods can declare exceptions using the throws keyword to indicate the method may throw that exception. 3. Exceptions can be caught in calling methods to handle exceptions thrown in other methods. This allows exceptions to be handled at an appropriate level without needing to handle them where they occur.

Uploaded by

Haseeb Chughtai
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 10

1.

An example of Try catch in Java


class Example1 {
public static void main(String args[]) {
int num1, num2;
try {
// Try block to handle code that may cause exception
num1 = 0;
num2 = 62 / num1;
System.out.println("Try block message");
} catch (ArithmeticException e) {
// This block is to catch divide-by-zero error
System.out.println("Error: Don't divide a number by zero");
}
System.out.println("I'm out of try-catch block in Java.");
}
}
Output:
Error: Don't divide a number by zero
I'm out of try-catch block in Java.

2. Example of Multiple catch blocks


class Example2{
public static void main(String args[]){
try{
int a[]=new int[7];
a[4]=30/0;
System.out.println("First print statement in try block");
}
catch(ArithmeticException e){
System.out.println("Warning: ArithmeticException");
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println("Warning: ArrayIndexOutOfBoundsException");
}
catch(Exception e){
System.out.println("Warning: Some Other exception");
}
System.out.println("Out of try-catch block...");
}
}
Output:
Warning: ArithmeticException

Out of try-catch block...

3. Examples of throws statement


Following statement will give an error:
public class NewClass {
public static void main(String[] args) {
ThrowingException obj=new ThrowingException();
obj.abc();
}
}
class ThrowingException{
void abc()throws Exception{
System.out.println("this method can throw exception");
}
}

to avoid this error we have to put the call to abc () method in try catch block; in
other words, handle the exception

public class NewClass {

public static void main(String[] args) {


try{
ThrowingException obj=new ThrowingException();
obj.abc();
}
catch (Exception e){

System.out.println("the method has thrown exception"+e.toString());


}
}
}
// next class

class ThrowingException{
void abc()throws Exception{
System.out.println("this method can throw exception");

}
}
output: this method can throw exception

4. What will happen if the method actually throws Exception?


public class NewClass {
public static void main(String[] args) {
try{
ThrowingException obj=new ThrowingException();
obj.abc();
}
catch (Exception e){
System.out.println("the method has thrown exception"+e.toString());
}
}
}
class ThrowingException{
void abc()throws Exception{
System.out.println("this method can throw exception");
int a=4/0;
}
}
output: this method can throw exception
the method has thrown exceptionjava.lang.ArithmeticException: / by zero

5. Another example to show that we can use throws statement (declare


exception) in abstract method:
public class NewClass {

public static void main(String[] args) {


try{
childThrowingException obj=new childThrowingException();
obj.abc();
}
catch (Exception e){

System.out.println("the method has thrown exception"+e.toString());


}
}
}
///////////////////////////
abstract class ParentThrowingException{
abstract void abc() throws Exception;// an abstract method can have throws
statement
}
/////////////////////////
class childThrowingException extends ParentThrowingException{
void abc()throws Exception{
System.out.println("this method can throw exception");
int a=4/0;
}
}
Output: this method can throw exception
the method has thrown exceptionjava.lang.ArithmeticException: / by zero

CONGRATS S2 EXAM EXCEPTION HANDLING SYLLABUS IS DONE!!!!!!!!!!!


6. We can inherit user defined type of exception from class Exception class e.g.
class MyException extends 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;}

void subtract(int pt) {


if (pt>points)
throw new MyException();
else points-=pt;
}
}
/////
public class GameTest {
public static void main(String args[]){
try{
Game account = new Game();
account.points = 500;
account.subtract(5000);

}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 */ }

8. Examples of Try catch finally blocks


Example 1: Below example illustrates finally block when no exception occurs in try block
class Example1{
public static void main(String args[]){
try{
System.out.println("First statement of try block");
int num=45/3;
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:
finally block
Out of try-catch-finally block

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

Examples of catching an exception in the calling method


Example 1: Below example illustrates finally block when no exception occurs in try block
class Example1
{
public static void myMethod()
{
try
{
int []arr = {3,4,2,1,5};
arr[7] = 9;

}
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

You might also like