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

CH3 Programs

The document contains code snippets that demonstrate handling exceptions in Java using try-catch blocks and throwing custom exceptions. Some key examples include: 1) Catching ArrayIndexOutOfBoundsException and NoSuchMethodException when accessing an array and calling a method. 2) Catching InterruptedException and IllegalArgumentException and handling them. 3) Throwing a custom PowerException for invalid power method inputs and catching it. 4) Throwing a custom caseSensitiveException if a command line argument does not start with an uppercase letter. 5) Throwing a custom MyException2 if an integer parameter passed to a compute method is greater than 10.

Uploaded by

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

CH3 Programs

The document contains code snippets that demonstrate handling exceptions in Java using try-catch blocks and throwing custom exceptions. Some key examples include: 1) Catching ArrayIndexOutOfBoundsException and NoSuchMethodException when accessing an array and calling a method. 2) Catching InterruptedException and IllegalArgumentException and handling them. 3) Throwing a custom PowerException for invalid power method inputs and catching it. 4) Throwing a custom caseSensitiveException if a command line argument does not start with an uppercase letter. 5) Throwing a custom MyException2 if an integer parameter passed to a compute method is greater than 10.

Uploaded by

Jagani Shrushti
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 21

CH_03_JAVA_QB_Solution

/* Contact your concern faculty for any query/error in code*/

/*

* Write a program to handle NoSuchMethodException, ArrayIndexOutofBoundsException using try-catch-finally


and throw.

*/

// Importing generic Classes/Files

import java.util.*;

public class Q_86

static void m1()

System.out.println("m1 method");

public static void main(String args[])

Scanner s = new Scanner(System.in);

int arr[] = new int[5];

try

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

arr[i] = s.nextInt();

String.class.getMethod("m2");

catch (ArrayIndexOutOfBoundsException e)

System.out.println("Array Bounds Exceeded...\nTry Again");

catch (NoSuchMethodException e){


System.out.println(e);

/*

* Q_87: Write a program to handle InterruptedException, IllegalArgumentException using try-cat-finally and throw

*/

import java.util.Scanner;

public class Q_87

public static void main(String[] args)

Scanner sc = new Scanner(System.in);

System.out.println("Hello");

try

Thread.sleep(5000);

catch(InterruptedException e)

System.out.println("InterruptedException handeled ");

System.out.println("Hi");
try

System.out.println("Enter an integer value: ");

int m = sc.nextInt();

if (m < 0 || m > 100)

throw new IllegalArgumentException("value must be non-negative and below 100");

System.out.println( "m = " + m);

catch(IllegalArgumentException i)

System.out.println("Enter valid Input");

finally

System.out.println("Both Exceptions are handeled");

/*

* Q_88: Write a method for computing x ^ y by doing repetitive multiplication. x and y are of type integer and are
to be given as command line arguments. Raise and handle exception(s) for invalid values of x and y. Also define
method main.

*/

class powerException extends Exception

powerException(String s)

super(s);

}
}

class Q_88

void power(int x , int y)

long p = 1;

for (int i = 1 ; i <=y ; i++)

p=p*x;

class mainQ_88

public static void main(String[] args)

try

int x = Integer.parseInt(args[0]);

int y = Integer.parseInt(args[1]);

Q_88 ob88 = new Q_88();

ob88.power(x, y);

catch(RuntimeException e)

System.out.println("INVALID INPUT!!");

}
/*

* Q_89: Write an application that searches through its command-line argument. If an argument is found that does
not begin with and upper case letter, display error message and terminate.

*/

class caseSensitiveException extends RuntimeException

caseSensitiveException(String s)

super(s);

public class Q_89

public static void main(String[] args)

String s = args[0] ;

char c = s.charAt(0);

System.out.println(c);

if ( !(c>=65 && c <= 90) )

throw new caseSensitiveException("INVALID UNPUT!!!");

/*

*Q_90: Write a program to create user define exception MyException2. Define a class ExceptionDemo2, that has a
method named compute(int a ) which throws a MyException object, when compute(int a )’s integer parameter is
greater than 10

*/

import java.util.Scanner;

class MyException2 extends RuntimeException


{

MyException2(String s)

super(s);

class ExceptionDemo2

void compute(int a)

if(a > 10)

throw new MyException("Entry Error !!!");

else

System.out.println("Valid Input");

class runQ_90

public static void main(String[] args)

Scanner sc = new Scanner (System.in);

ExceptionDemo2 ob = new ExceptionDemo2();

System.out.println("Enter any integer input");

int n = sc.nextInt();

ob.compute(n);

}
// Q_91 //using Scanner

import java.util.Scanner;

class InvalidStatusException extends Exception {

public InvalidStatusException(String s) {

super(s);

class ResourcesStatus {

private int[][] statusRef;

public ResourcesStatus() {

statusRef = new int[3][3];

for (int i = 0; i < 3; i++) {

for (int j = 0; j<3;j++){

try {

Scanner sc = new Scanner(System.in);

int status = sc.nextInt();

if (status < 0 || status > 2) {

throw new InvalidStatusException("Invalid status value: " + status);

statusRef[i][j] = status;

} catch (Exception e) {

System.out.println("Error: " + e.getMessage() + ". Setting status to free (0).");

statusRef[i][j] = 0;

}
public void processStatusCount() {

int freeCount = 0, occupiedCount = 0, inaccessibleCount = 0;

for (int i = 0; i < 3; i++) {

for (int j = 0; j < 3; j++) {

switch (statusRef[i][j]) {

case 0:

freeCount++;

break;

case 1:

occupiedCount++;

break;

case 2:

inaccessibleCount++;

break;

System.out.println("Free resources: " + freeCount);

System.out.println("Occupied resources: " + occupiedCount);

System.out.println("Inaccessible resources: " + inaccessibleCount);

if (occupiedCount > freeCount) {

System.out.println("Error: total number of occupied resources exceeds total number of free resources.");

for (int i = 0; i < 3; i++) {

for (int j = 0; j < 3; j++) {

if (statusRef[i][j] == 2) {

statusRef[i][j] = 0;

System.out.println("All inaccessible resources marked as free.");


}

class Main1 {

public static void main(String[] args) {

System.out.println("Enter 9 Inputs: ");

ResourcesStatus resourcesStatus = new ResourcesStatus();

resourcesStatus.processStatusCount();

/************************************* CLA
******************************************************/

class InvalidStatusException extends Exception {

public InvalidStatusException(String message) {

super(message);

class ResourcesStatus {

private int[][] statusRef;

public ResourcesStatus(String[] initialStatus) {

statusRef = new int[3][3];

for (int i = 0; i < 9; i++) {

int row = i / 3;

int col = i % 3;

try {

int status = Integer.parseInt(initialStatus[i]);

if (status < 0 || status > 2) {

throw new InvalidStatusException("Invalid status value: " + status);


}

statusRef[row][col] = status;

} catch (NumberFormatException | InvalidStatusException e) {

System.out.println("Error: " + e.getMessage() + ". Setting status to free (0).");

statusRef[row][col] = 0;

public void processStatusCount() {

int freeCount = 0, occupiedCount = 0, inaccessibleCount = 0;

for (int i = 0; i < 3; i++) {

for (int j = 0; j < 3; j++) {

switch (statusRef[i][j]) {

case 0:

freeCount++;

break;

case 1:

occupiedCount++;

break;

case 2:

inaccessibleCount++;

break;

System.out.println("Free resources: " + freeCount);

System.out.println("Occupied resources: " + occupiedCount);

System.out.println("Inaccessible resources: " + inaccessibleCount);

if (occupiedCount > freeCount) {

System.out.println("Error: total number of occupied resources exceeds total number of free resources.");
for (int i = 0; i < 3; i++) {

for (int j = 0; j < 3; j++) {

if (statusRef[i][j] == 2) {

statusRef[i][j] = 0;

System.out.println("All inaccessible resources marked as free.");

class Main {

public static void main(String[] args) {

if (args.length != 9) {

System.out.println("Error: expected 9 arguments, got " + args.length);

return;

ResourcesStatus resourcesStatus = new ResourcesStatus(args);

resourcesStatus.processStatusCount();

}/*

*Q_92: Write a complete program to accept N integer numbers from the command line. Raise and handle
exceptions for following cases :-

when a number is –ve-

when a number is evenly divisible by 10

- when a number is greater than 1000 and less than 2000

- when a number is greater than 7000

Skip the number if an exception is raised for it, otherwise add it to find total sum

*/

class invalidException extends RuntimeException

{
invalidException(String s)

super(s);

public class Q_92

public static void main(String[] args)

int sum = 0 ;

for(int i = 0 ; i < args.length ; i++)

int n = Integer.parseInt(args[i]);

if ( n < 0)

try

throw new invalidException("Negative value");

catch(invalidException e)

continue;

if ( n % 10 == 0)

try

throw new invalidException("Divisible by 10");

}
catch(invalidException e)

continue;

if( n > 1000 && n<2000)

try

throw new invalidException("number is greater than 1000 and less than 2000");

catch(invalidException e)

continue;

if( n > 7000 )

try

throw new invalidException("number is greater than 7000");

catch(invalidException e)

continue;

}
else

sum =sum +n ;

System.out.println("Sum = " + sum);

/*

*Q_93: Declare a class called coordinate to represent 3 dimensional Cartesian coordinates( x, y and z).Define
following methods:- constructor- display, to print values of members- add_coordinates, to add three such
coordinate objects to produce a resultantcoordinate object. Generate and handle exception if x, y and z
coordinates of the resultare zero. - main, to show use of above methods.

*/

class coordinateZeroException extends RuntimeException

coordinateZeroException(String s)

super(s);

class coordinate

int x , y , z ;

coordinate(int x , int y , int z)

this.x = x ;

this.y = y ;

this.z = z ;

void display()

System.out.println("x coordinate = "+x);


System.out.println("y coordinate = "+y);

System.out.println("z coordinate = "+z);

void add_coordinates(coordinate ob1 , coordinate ob2 , coordinate ob3)

coordinate res = new coordinate(x, y, z) ;

res.x = ob1.x + ob2.x +ob3.x ;

res.y = ob1.y + ob2.y +ob3.y ;

res.z = ob1.z + ob2.z +ob3.z ;

try

if(res.x == 0 && res.y == 0 && res.z == 0)

throw new coordinateZeroException("Resultaant coordinate's x , y z values are zero");

else

res.display();

catch(Exception e)

System.out.println("Exception Handling done!!");

class resultantcoordinate

public static void main(String[] args)

coordinate ob1 = new coordinate(0, 0, 0);

coordinate ob2 = new coordinate(0, 15, 0);


coordinate ob3 = new coordinate(2, 0, 5);

coordinate ob4 = new coordinate(0, 0, 0);

ob4.add_coordinates(ob1, ob2, ob3);

}/*

*Q_94: Write a program to handle NullPointerException.

*/

public class Q_94

public static void main(String[] args)

String s = null ;

try

System.out.println(s.length());

catch(NullPointerException e)

System.out.println("Exception Handeling Done!!");

/*

*Q_95: Write a program to create user define exception MyException.

* Define a class ExceptionDemo that has a method named compute( ) which

* throws a MyException object, when compute( )’sinteger parameter is divisible by 7 and

* not divisible by 5.

*/

import java.util.Scanner;

class MyException extends RuntimeException

MyException(String s)
{

super(s);

class ExceptionDemo

void compute(int a)

if(a % 7 == 0 && a % 5 != 0)

throw new MyException("Entry Error !!!");

else

System.out.println("Valid Input");

class runQ_95

public static void main(String[] args)

Scanner sc = new Scanner (System.in);

ExceptionDemo ob = new ExceptionDemo();

System.out.println("Enter any integer input");

int n = sc.nextInt();

ob.compute(n);

/*

*Q_96: Write an application that searches through its command-line argument.


* If any of command line argument is found nagative then display error message.

*/

class negativeException extends RuntimeException

negativeException(String s)

super(s);

public class Q_96

public static void main(String[] args)

int a = Integer.parseInt(args[0]);

if( a < 0)

throw new negativeException("first input is negative : Invalid");

else

System.out.println("Input is " + a);

/*

* Q_97 : Write an application that searches through its command-line argument.

* If first command line argument is found zero then display error message.

*/
class entryException9 extends RuntimeException

entryException9(String s)

super(s);

public class Q_97

public static void main(String[] args)

int a = Integer.parseInt(args[0]);

if( a == 0)

throw new entryException9("first input is 0 : Invalid");

else

System.out.println("Input is " + a);

}/*

*Q_98 : Write an application that searches through its command-line argument.

* If sum of first and second command line argument is found 10 then display error message.

*/

class entryException extends RuntimeException

entryException(String s)

{
super(s);

public class Q_98

public static void main(String[] args)

int a = Integer.parseInt(args[0]);

int b = Integer.parseInt(args[1]);

int c = a+b ;

if( c == 10)

throw new entryException("Sum of input is 10 : Invalid");

else

System.out.println("Sum is " + c);

/*

* Q_99 : write a program to enter the five subject marks out of 100 of student.

* If any subject marks is less than 35 then programm will generate exception

*/

import java.util.Scanner;

class failException extends RuntimeException

failException(String s)

super(s);
}

class Q_99

public static void main(String[] args)

Scanner sc = new Scanner(System.in);

double marks[] = new double[5];

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

System.out.println("Enter marks of subject " + (i+1));

marks[i] = sc.nextDouble();

if(marks[i] < 35)

throw new failException("Sorry You are failed");

else

continue;

System.out.println("Congratulations You have Passed This Semester!!");

//this is for reference only for better preparations and there may be some errors. Don’t consider it as final solution.

You might also like