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

OOP LAB Assignment-07

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

OOP LAB Assignment-07

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

OOP LAB

B. Tech. CSE 5th Sem


Session: July-Dec 2024
Faculty: Debashis Dev Misra

Assignment # 07: Exception Handling in Java

1. Write a Java program to handle Array Index out of Bounds error.


2. Write a Java program to handle divide-by-zero.
3. Write a Java program to validate Age using user-defined exception.
4. Write a Java program to check withdrawal limit using user-defined exception.
5. Write a Java program to check Odd numbers using user-defined exception.
6. Write a Java program to validate email ID using user-defined exception.
7. Write a Java program to create user-defined exception for marks entered, when marks
entered is negative or greater than max marks.
8. Write a Java program to create user-defined exception for email-is entered, when e-
mail id entered is not in proper format.
Exception Handling in Java
The Exception Handling in Java is one of the powerful mechanism to handle the runtime
errors so that normal flow of the application can be maintained.
Here we will learn about Java exceptions, its type and the difference between checked and
unchecked exceptions.
What is Exception in Java
Dictionary Meaning: Exception is an abnormal condition.
In Java, an exception is an event that disrupts the normal flow of the program. It is an object
which is thrown at runtime.
What is Exception Handling
Exception Handling is a mechanism to handle runtime errors such as
ClassNotFoundException, IOException, SQLException, RemoteException, etc.
Advantage of Exception Handling
The core advantage of exception handling is to maintain the normal flow of the
application. An exception normally disrupts the normal flow of the application that is why
we use exception handling. Let's take a scenario:
1. statement 1;
2. statement 2;
3. statement 3;
4. statement 4;
5. statement 5;//exception occurs
6. statement 6;
7. statement 7;
8. statement 8;
9. statement 9;
10. statement 10;
Suppose there are 10 statements in your program and there occurs an exception at statement
5, the rest of the code will not be executed i.e. statement 6 to 10 will not be executed. If we
perform exception handling, the rest of the statement will be executed. That is why we use
exception handling in Java.
Hierarchy of Java Exception classes
The java.lang.Throwable class is the root class of Java Exception hierarchy which is inherited
by two subclasses: Exception and Error. A hierarchy of Java Exception classes are given
below:
Types of Java Exceptions
There are mainly two types of exceptions: checked and unchecked. Here, an error is
considered as the unchecked exception. According to Oracle, there are three types of
exceptions:
1. Checked Exception
2. Unchecked Exception
3. Error
Difference between Checked and Unchecked Exceptions
1) Checked Exception
The classes which directly inherit Throwable class except RuntimeException and Error are
known as checked exceptions e.g. IOException, SQLException etc. Checked exceptions are
checked at compile-time.
2) Unchecked Exception
The classes which inherit RuntimeException are known as unchecked exceptions e.g.
ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc.
Unchecked exceptions are not checked at compile-time, but they are checked at runtime.
3) Error
Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc.

Java Exception Keywords


There are 5 keywords which are used in handling exceptions in Java.
Keywor
Description
d
The "try" keyword is used to specify a block where we should place exception code.
try The try block must be followed by either catch or finally. It means, we can't use try
block alone.
The "catch" block is used to handle the exception. It must be preceded by try block
catch which means we can't use catch block alone. It can be followed by finally block
later.
The "finally" block is used to execute the important code of the program. It is
finally
executed whether an exception is handled or not.
throw The "throw" keyword is used to throw an exception.
The "throws" keyword is used to declare exceptions. It doesn't throw an exception. It
throws specifies that there may occur an exception in the method. It is always used with
method signature.

Programming Exercises:
1. Write a Java program to handle Array Index out of Bounds error.
public class ArrayIndexTest
{
public static void main(String[ ] args)
{
int[] myNumbers = {1, 2, 3};
//System.out.println(myNumbers[10]);
try
{
System.out.println(myNumbers[10]);
}
catch (Exception e)
{
System.out.println("Something went wrong.");
System.err.println(e);
//java.lang.ArrayIndexOutOfBoundsException: Index 10 out of bounds
for length 3
System.out.println(e.getMessage()); //Index 10 out of bounds for length
3
}
finally
{
System.out.println("This is the FINALLY block..");
}
}
}

2. Write a Java program to handle divide-by-zero.


public class DivideByZero
{
public static void main(String[] args)
{
try
{
// code that generates exception
float x = 5 / 0;
}

catch (ArithmeticException e)
{
System.out.println("Exception: " + e);
System.out.println("Exception message : " + e.getMessage());
}

finally
{
System.out.println("This is the finally block");
}
}
}

3. Write a Java program to validate Age using user-defined exception.


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

class InvalidAgeException extends Exception


{
InvalidAgeException(String s)
{
super(s);
}
}

class TestCustomException
{
static void validateAge(int age) throws InvalidAgeException
{
if(age<18)
throw new InvalidAgeException("Age not valid");
else
System.out.println("welcome to vote");
}

public static void main(String args[]) throws IOException


{
BufferedReader reader =new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter your age: ");
int age = Integer.parseInt(reader.readLine());
try
{
validateAge(age);
}
catch(Exception m)
{
System.out.println("Exception occured: "+m);
}

finally
{
System.out.println("Program comes to end");
}
}
}
4. Write a Java program to check withdrawal limit using user-defined
exception.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

class LowBalanceException extends Exception


{
// creating a constructor to print the message
LowBalanceException(String messageOfException)
{
super(messageOfException); // message passing to super class which is Exception
}
}
class WithdrawalLimitException extends Exception
{
// creating a constructor to print the message
WithdrawalLimitException(String messageOfException)
{
super(messageOfException); // message passing to super class which is Exception
}
}

class CashWithdraw
{
static void validateAmount(int amount)
{
if(amount < 500)
{
try
{
throw new LowBalanceException("You can't withdraw if amount is less
than 500");
}
catch (LowBalanceException e1)
{
e1.printStackTrace();
}
}
else if (amount >10000)
{
try
{
throw new WithdrawalLimitException("You can't withdraw if amount is greater
than 10000");
}
catch (WithdrawalLimitException e2)
{
e2.printStackTrace();
}
}

else
System.out.println("Withdrawal permitted..");
}

public static void main(String args[]) throws IOException


{
BufferedReader reader =new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter amount: ");
int amount = Integer.parseInt(reader.readLine());
validateAmount(amount);
System.out.println("Thanks for using the ATM");
}
}

5. Write a Java program to check Odd numbers using user-defined exception.


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

class OddNumberException extends Exception // Statement 1


{
OddNumberException()
{
super("Odd number exception");
}
OddNumberException(String msg)
{
super(msg);
}
}

class OddNumberCheck
{
public static void main(String args[]) throws IOException
{
BufferedReader reader =new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter any number: ");
int num = Integer.parseInt(reader.readLine());
try
{
if(num%2 != 0)
throw(new OddNumberException()); // Statement 2
else
System.out.println("\n\t" + num + " is an even number");
}
catch(OddNumberException Ex)
{
System.out.println("\n\tError : " + Ex.getMessage());
}

System.out.println("Program comes to end...");


}
}
6. Write a Java program to validate email ID using user-defined exception.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

class InvalidEmailException extends Exception


{
InvalidEmailException(String s)
{
super(s);
}
}

class ValidateEmail
{
static void validateEmailID(String email) throws InvalidEmailException
{
if(email.length()<3)
throw new InvalidEmailException("Email ID not valid... too few characters");
else if(email.indexOf('@')<2)
throw new InvalidEmailException("Email ID not valid... @ not found or improper
position");
else if(email.indexOf('.')<(email.indexOf('@')+2))
throw new InvalidEmailException("Email ID not valid .. @ and . cannot come
together");
else
System.out.println("Email ID validated..");
}

public static void main(String args[]) throws IOException


{
BufferedReader reader =new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter Email ID: ");
String email_id = reader.readLine();
try
{
validateEmailID(email_id);
}
catch(Exception m)
{
System.out.println("Exception occurred: "+m);
}
finally
{
System.out.println("Program comes to end");
}
}
}

User-defined Custom Exception in Java


Why use custom exceptions?

Java exceptions cover almost all the general types of exceptions that may occur in the
programming. However, we sometimes need to create custom exceptions.

Following are a few of the reasons to use custom exceptions:

• To catch and provide specific treatment to a subset of existing Java exceptions.


• Business logic exceptions: These are the exceptions related to business logic and
workflow. It is useful for the application users or the developers to understand the
exact problem.

In order to create a custom exception, we need to extend the Exception class that belongs to
java.lang package.

Example: We pass the string to the constructor of the superclass- Exception which is
obtained using the “getMessage()” function on the object created.

// A Class that represents use-defined exception

class MyException extends Exception {


public MyException(String s)
{
// Call constructor of parent Exception
super(s);
}
}

// A Class that uses above MyException


public class Main {
// Driver Program
public static void main(String args[])
{
try {
// Throw an object of user defined exception
throw new MyException("GeeksGeeks");
}
catch (MyException ex) {
System.out.println("Caught");

// Print the message from MyException object


System.out.println(ex.getMessage());
}
}
}
Programming Exercises:
7. Write a Java program to create user-defined exception for marks entered,
when marks entered is negative or greater than max marks.
8. Write a Java program to create user-defined exception for email-is entered,
when e-mail id entered is not in proper format.

You might also like