Exception Handling

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 7

NAME: AREEBA SAJID

ENROLLMENT: 02-132212-036

LAB NO. 13 COURSE: BCE- 3(A)

EXAMPLE:

SOLUTION:

package exception;

public class Exception {

public static void main(String[] args) {

try{

int a=10;

int b=0;

int c= a/b;

System.out.println("the result is "+c);

catch(ArithmeticException e)

System.out.println("Divide by zero is not possible");

}
}

RESULT:

1. To create your own Exception to check whether a number is

a) Even or odd

SOLUTION:

package exception;

import java.util.Scanner;

public class Exception {

public static void main(String[] args) {

Scanner reader = new Scanner(System.in);

System.out.print("Enter a number: ");

int num = reader.nextInt();


if(num % 2 == 0 )

throw new ArithmeticException("The number is even");

else

System.out.println(num + " is odd");

}}

RESULT:

b) Prime or not

SOLUTION:

package arithmeticexception_demo;

public class ArithmeticException_Demo {

public static void main(String[] args) {


int a= 0;

int i,m=0,flag=0;

m=a/2;

if(a==0||a==1)

throw new ArithmeticException("is not a prime number");

else

for(i=2;i<=m;i++)

if(a%i==0)

System.out.println(a+"is not a prime number..");

flag=1;

break;

if(flag==0)

System.out.println(a+"is a prime number...");

}
}

RESULT:

2. To illustrate Arithemtic Exception, ArrayIndexOut Of BoundsEcxeption,Negative array size Exception


using Try and catch Block with suitable example?

SOLUTION:

package exception;

public class Exception {

public static void main(String[] args) {

try

int a[]= new int[5];

a[10]=1;

catch(ArrayIndexOutOfBoundsException e)

System.out.println("the array is out of bound");

}
}}

RESULT:

3. Write a program that count how many prime numbers between minimum and maximum values
provided by user. If minimum value is greater than or equal to maximum value, the program should
throw a InvalidRange exception and handle it to display a message to the user on the following
format:Invalid range: minimum is greater than or equal to maximum.

SOLUTION:

package exception;

public class Exception {

public static void main(String[] args) {

int a= 13;

int i,m=0,flag=0;

m=a/2;

if( a>1 && a<15)

throw new ArithmeticException("is out of range");

else
{

for(i=2;i<=m;i++)

if(a%i==0)

System.out.println(a+"is not a prime number..");

flag=1;

break;

}}

RESULT:

You might also like