0% found this document useful (0 votes)
2 views4 pages

Exception Examples

The document contains multiple Java classes demonstrating exception handling using try-catch blocks. It includes examples of handling specific exceptions like IndexOutOfBoundsException and ArithmeticException, as well as using multiple catch blocks and nested try blocks. Each example illustrates how exceptions can be caught and handled to prevent program crashes.

Uploaded by

ry726301
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views4 pages

Exception Examples

The document contains multiple Java classes demonstrating exception handling using try-catch blocks. It includes examples of handling specific exceptions like IndexOutOfBoundsException and ArithmeticException, as well as using multiple catch blocks and nested try blocks. Each example illustrates how exceptions can be caught and handled to prevent program crashes.

Uploaded by

ry726301
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

1-

class ListOfNumbers {
public int[] arr = new int[10];
public void writeList() {
try {
arr[10] = 11;
}
catch (NumberFormatException e1) {
[Link]("NumberFormatException => " + [Link]());
}
catch (IndexOutOfBoundsException e2) {
[Link]("IndexOutOfBoundsException=>"+ [Link]());
}

}
}
class Main {
public static void main(String[] args) {
ListOfNumbers list = new ListOfNumbers();
[Link]();
}
}
2-

public class TryCatchExample9 {


public static void main(String[] args) {
try
{
int arr[]= {1,3,5,7};
[Link](arr[10]); //may throw exception
}
// handling the array exception
catch(ArrayIndexOutOfBoundsException e)
{
[Link](e);
}
[Link]("rest of the code");
}

}
3- Multiple Catch Block

public class MultipleCatchBlock1 {

public static void main(String[] args) {

try{
int a[]=new int[5];
a[5]=30/0;
}
catch(ArithmeticException e)
{
[Link]("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
[Link]("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{
[Link]("Parent Exception occurs");
}
[Link]("rest of the code");
}
}
4- Nested Try

public class NestedTryBlock{


public static void main(String args[]){
//outer try block
try{
//inner try block 1
try{
[Link]("going to divide by 0");
int b =39/0;
}
//catch block of inner try block 1
catch(ArithmeticException e){
[Link](e);
}
//inner try block 2
try{
int a[]=new int[5];
//assigning the value out of array bounds
a[5]=4;
}
//catch block of inner try block 2
catch(ArrayIndexOutOfBoundsException e) {
[Link](e);
}
[Link]("other statement");
}
//catch block of outer try block
catch(Exception e) {
[Link]("handled the exception (outer catch)");
}
[Link]("normal flow..");
}
}

You might also like