0% found this document useful (0 votes)
4 views3 pages

JPR 13

The document provides examples of using the 'throw' and 'throws' clauses in Java for exception handling. It demonstrates how to create custom exceptions and handle them, including a specific case for a 'NotMatchExceptions' when a string does not match 'India'. Each example includes a main method that tests the exception handling and outputs relevant messages.

Uploaded by

shindearyan226
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)
4 views3 pages

JPR 13

The document provides examples of using the 'throw' and 'throws' clauses in Java for exception handling. It demonstrates how to create custom exceptions and handle them, including a specific case for a 'NotMatchExceptions' when a string does not match 'India'. Each example includes a main method that tests the exception handling and outputs relevant messages.

Uploaded by

shindearyan226
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/ 3

1. Demonstrate use of throw and throws clause.

class Timepass {
public static void checkAge(int age) throws ArithmeticException {
if (age < 18) {
throw new ArithmeticException("Not eligible to vote");
} else {
System.out.println("Eligible to vote");
}
}

public static void main(String[] args) {


try {
checkAge(16);
} catch (ArithmeticException e) {
System.out.println("Exception caught: " + e.getMessage());
}
}
}

OUTPUT:

3. Write the simple program for throwing our own exceptions.


class CustomException extends Exception {
public CustomException(String message) {
super(message);
}
}

public class MainExceptionDemo {


public static void main(String[] args) {
try {
System.out.println("Inside main method...");
throw new CustomException("Custom Exception Thrown()");
}
catch (CustomException e) {
System.out.println(e.getMessage());
}
}
}

OUTPUT:

4. Define an exception called “NotMatchExceptions” that is thrown when a


string is not equals to “India”. Write a program that uses this exceptions.
import java.util.*;

class NotMatchExceptions extends Exception{


public NotMatchExceptions(String Msg){
super(Msg);
}
}

class StringThrow{
public void getstring() throws NotMatchExceptions{
String strm = "India";
String getstr;
Scanner sc = new Scanner(System.in);
System.out.println("Enter a Password: ");
getstr = sc.nextLine();

if(getstr.equals(strm)){
System.out.println("Correct String!!");
}
else{
throw new NotMatchExceptions("String Not Matched!!");
}
}
public static void main(String[] args){
StringThrow obj = new StringThrow();
try{
obj.getstring();
}
catch(NotMatchExceptions e){
System.out.println(e.getMessage());
}

}
}

OUTPUT:

You might also like