[go: up one dir, main page]

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

Exception Handling

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

Exception Handling

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

EXPERIMENT 12

//EXCEPTION HANDLING

PROGRAM:

import java.util.*;

public class JavaExceptionExample{

public static void main(String args[]){

try{

//code that may raise exception

int data=100;

int divide;

Scanner sc= new Scanner(System.in);

System.out.print("Enter data: ");

divide=sc.nextInt();

data=data/divide;

}catch(ArithmeticException f){

System.out.println(f);

//rest code of the program

System.out.println("rest of the code...");

OUTPUT:

java -cp /tmp/VVidP83rl6 JavaExceptionExample

Enter data: 0

java.lang.ArithmeticException: / by zero

rest of the code...

java -cp /tmp/VVidP83rl6 JavaExceptionExample

Enter data: 5

20

rest of the code...

// MULTIPLE CATCH
PROGRAM:

import java.util.*;

public class MultipleCatch

public static void main(String args[])

try{

Scanner sc=new Scanner(System.in);

int[] a;

a= new int[5];

int x;

int quotient;

System.out.print("Enter the value of divisor: ");

x=sc.nextInt();

System.out.print("Enter 5 values: ");

for (int i=0;i<5;i++)

{ try{

System.out.print("Enter "+(i+1)+"\n");

a[i]=sc.nextInt();

quotient=a[i]/x;

System.out.print(quotient);

} catch (ArithmeticException e){

//System.out.print(e);

} } }

catch (ArithmeticException e){

System.out.print(e);

catch (ArrayIndexOutOfBoundsException f){

System.out.print("Array index out of bound.");

catch(Exception z)
{

System.out.print("Parent exception case.");

System.out.print("\nAfter using the exception handling, the rest of the code works fine!");

OUTPUT:

java -cp /tmp/VVidP83rl6 MultipleCatch

Enter the value of divisor: 0

Enter 5 values: Enter 1

12

Enter 2

85

Enter 3

13

Enter 4

Enter 5

After using the exception handling, the rest of the code works fine!

// throw keyword for exception

PROGRAM:

class A{

public static void print(int age){

if (age<18){

throw new ArithmeticException("Invalid age"); }

else{

System.out.print("You are eligible to vote."); } }

public static void main(String args[])

{ print(3);

System.out.print("Even afte incorrect parameter the code still works.");


}

OUTPUT:

java -cp /tmp/2DQWVy5akQ A

Exception in thread "main" java.lang.ArithmeticException: Invalid age

at A.print(A.java:7)

at A.main(A.java:16)

Even after incorrect parameter the code still works.

You might also like