parajulirajesh.com.np

Assignment

Hand Written Study Materials

program example to implement throw keyword used to throw an exception explicity program example

public class ThrowExample {

// Method to divide two numbers
static int divide(int a, int b) {
if (b == 0) {
// Explicitly throwing an exception
throw new ArithmeticException(“Cannot divide by zero!”);
}
return a / b;
}

public static void main(String[] args) {
try {
int result = divide(10, 0); // Will trigger the exception
System.out.println(“Result: ” + result);
} catch (ArithmeticException e) {
System.out.println(“Exception caught: ” + e.getMessage());
}

System.out.println(“Program continues…”);
}
}

throws keyword used program example

public class DivideByZeroThrows {

// Method declaring exception using throws
static int divide(int a, int b) throws ArithmeticException {
return a / b; // May throw ArithmeticException
}

public static void main(String[] args) {
try {
int result = divide(10, 0); // Calling method
System.out.println(“Result: ” + result);
} catch (ArithmeticException e) {
System.out.println(“Exception handled: Cannot divide by zero.”);
}

System.out.println(“Program continues…”);
}
}

Scroll to Top

Rajesh Parajuli

BICTE GMC

LEC.RAJESH PARAJULI

Address: Ghodaghodi Municipality-1 Sukhad kailali

Contact: 9847546279

Ghodaghodi Multiple Campus BICTE