Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 3

Practical No.

26 & 27
Program Code: Program using ‘throw’ and ‘throws’ clause
class Main {

static void check () throws ArithmeticException {

System.out.println("Inside check function");

throw new ArithmeticException("Demo");

public static void main (String args []) {

try {

check ();

} catch (ArithmeticException e) {

System.out.println("Caught " + e);

}}}

Practical Related Questions:


3) Write a simple program for throwing our own exceptions?
public class Main2{

static void checkAge (int age) {

if (age < 18) {

throw new ArithmeticException ("Access Denied - You must be atleast 18 years old");

} else {

System.out.println("Access granted - You are old enough")

}}

public static void main (String args []) {

checkAge (15);

}}
Exercise:
1) Define an exception called "NotMatchException" that is thrown when a string is not equal
to "India". Write a program that uses this exception
import java.lang.Exception;

import java.util.*;

class NotMatchException extends Exception {

public NotMatchException () {

super ("String is not equal");

}}

class India {

public static void main (String args[]) {

String Str;

Scanner S=new Scanner (System.in);

try {

System.out.print("Enter the String = ");

Str=S.next();

if (!Str.equals("India")) {

throw new NotMatchException ();

else {

System.out.println("String are equal");

catch (NotMatchException e) {

System.out.println(e);

}}}
2) Write the output of the following program:
class tst1{

public static void main (String args []) {

Thread.sleep(10000);

System.out.println("Hello Java");

}}

3) Write the output of the following program:


class tst2{

public static void main (String args []) throws InterruptedException {

Thread.sleep(10000);

System.out.println("Hello Java");

}}

You might also like