Module 4
QUESTION AND ANSWERS
Packages: Packages, Packages and Member Access, Importing Packages.
Exceptions: Exception-Handling Fundamentals,
Exception Types,
Uncaught Exceptions,
Using try and catch,
Multiple catch Clauses,
Nested try Statements,
throw, throws, finally, Java’s Built-in Exceptions,
Creating Your Own Exception subclasses,
Chained Exceptions.
1. Define a package. Explain how to create user defined package with an example.
Package is a folder containing classes, abstract classes and interfaces. Packages in Java are used to
organize code, avoid naming conflicts, and improve reusability and maintainability.
// File: [Link]
// Location: mypack/[Link]
package mypack;
public class MyPackageClass {
public void displayMessage() {
[Link]("Hello from MyPackageClass inside mypack!");
}
}
// File: [Link]
import [Link];
public class TestPackage {
public static void main(String[] args) {
MyPackageClass obj = new MyPackageClass();
[Link]();
}
}
Compilation :
javac [Link]
Output :
Hello from MyClass inside mypackage!
2. Examine the various levels of access protections available for packages and their implications
with suitable examples.
Or
Explain four categories of visibility for class members based on packages.
When subclass and super class are in different packages
When a class in one package extends a class in some other package,
Default methods and default data members cannot be inherited.
Private data members and methods also cannot be inherited.
Public and protected methods and data members can be inherited.
When subclass and super class are in same packages
When a class in one package extends another class in same package,
Default methods and default data members can be inherited.
Public and protected methods and data members can be inherited.
But Private data members and methods also cannot be inherited.
Java Access Modifiers and their scope:
Modifier Other class or
Within the In Subclasses in other Any class in other
subclass within same
Class packages packages
Package
public ✔ ✔ ✔ ✔
protected ✔ ✔ ✔ ✘
default ✔ ✔ ✘ ✘
private ✔ ✘ ✘ ✘
3. Build a Java program to create a package "balance” containing Account Class with
displayBalance ( ) method and import this package in another program to access method of
Account Class.
// filename : [Link]
// location : balance/[Link]
package balance;
public class Account {
private int balance;
public Account() {
balance = 1000;
}
public void displayBalance() {
[Link](balance);
}
}
// filename : [Link]
import balance.*;
public class BalanceDemo {
public static void main(String args[])
{
Account obj1 = new Account();
[Link]();
}
}
compilation command : javac [Link]
Automatically all the classes imported will be compiled.
4. Define Exception. Explain Exception handling mechanism in Java along with syntax and
example.
Exception is an error that occurs during execution or run time. It causes program to end abruptly or
crash. It is programmer’s responsibility to identify the statements that can cause exception and
handle them.
There are two types of exception -
Built-in exceptions – exceptions defined in java. Example -
ArithmeticException
NullPointerException
ArrayIndexOutofBoundsException
Custom exceptions – exceptions that are defined or specific to applications and are user
defined
Exceptions are handled using try-catch block in Java.
Syntax -
try {
// statements that can cause exception
}
catch (Exceptiontype1 obj) {
// statements
}
catch (Exceptiontype2 obj) {
// statements
}
…..
catch (Exception obj) {
}
finally {
// block that is executed after try block both when exceptions
// occur and do not occur
// it is optional
}
Example:
import [Link].*;
class ExceptionExample {
public static void main(String[] args)
{
Scanner sc = new Scanner([Link]);
int n, d, result;
n = [Link]();
d = [Link]();
try {
result = n/d;
[Link]("Result = " + result);
}
catch (ArithmeticException e) {
[Link](e);
}
}
}
5. Compare throw and throws keyword by providing suitable example program.
throw throws
Used to explicitly throw an exception Used to declare exceptions that a method might throw but
doesn’t handle.
Inside the method or code block Used in method declaration
Used for both checked and unchecked Mainly used for checked exceptions
exceptions
Example (throws) -
class ThrowExample {
public static void main(String[] args) throws InterruptedException
{
[Link](10);
}
}
Example (throw) -
import [Link].*;
class IPCCMarksException extends Exception {
IPCCMarksException(String msg) {
super(msg);
}
}
class ThrowExample {
public static void main(String[] args)
{
Scanner sc = new Scanner([Link]);
[Link]("Enter java IA1 marks ");
try {
int marks = [Link]();
if (marks > 30 || marks < 0)
throw new IPCCMarksException("Marks out of range 0-30");
}
catch (Exception e) {
[Link](e);
}
}
}
6. What is an exception? Explain the following:
try
catch
throw
throws
finally
Exception is an error that occurs during execution or run time. It causes program to end
abruptly or crash. It is programmer’s responsibility to identify the statements that can cause
exception and handle them.
(i) try
A try block contains the code that might throw an exception.
It is followed by one or more catch blocks or a finally block.
Syntax:
try {
// Code that may throw an exception
}
(ii) catch
A catch block handles the exception thrown in the try block. Each catch block specifies
the type of exception it can handle. There can be more than 1 catch for one try block
Syntax:
try {
int result = 10 / 0; // risky code
} catch (ArithmeticException e) {
[Link]("Division by zero is not allowed!");
}
(iii) throw
The throw keyword is used to explicitly throw an exception object. It is used inside
methods or blocks to signal an exception which can be built in exception or custom
exception.
Syntax:
throw new IOException("File not found");
(iv) throws
The throws keyword is used in a method declaration to specify the exceptions that the
method might throw. It informs the caller that they must handle or declare these
exceptions.
Syntax:
public void readFile() throws IOException {
// code that may throw IOException
}
v) finally
A finally block contains code that will always execute, regardless of whether an exception
occurred or not. Commonly used for resource cleanup (closing files, releasing connections,
etc.).
Syntax:
try {
int result = 10 / 2;
} catch (ArithmeticException e) {
[Link]("Error occurred!");
} finally {
[Link]("This block always executes.");
}
7. How do you create your own exception class? Explain with code snippet.
Custom exception is an exception that is defined by user and not covered by Java exceptions. It
allows to give meaningful error messages in an organized way.
Custom exceptions are created by
extending Exception class for checked exceptions
extending RuntimeException for unchecked exceptions
Custom exceptions must have one constructor with one string argument.
Custom exceptions can have data members or methods like any other class.
Example :
class DivisionByZeroException extends Exception {
public DivisionByZeroException(String message) {
super(message);
}
}
public class CustomExceptionDemo {
static double divide(int numerator, int denominator) throws
DivisionByZeroException {
if (denominator == 0) {
throw new DivisionByZeroException("Cannot divide by zero");
}
return (double)numerator/denominator;
}
public static void main(String[]args) {
int numerator = 10;
int denominator = 20;
try {
double result = divide(numerator, denominator);
[Link]("Result of division : " + result);
}
catch(DivisionByZeroException e) {
[Link]("Exception caught : "+[Link]());
}
finally {
[Link]("Finally block executed");
}
}
}
8. Develop a Java program to raise a custom exception for division by zero using try, catch,
throw and finally.
class DivisionByZeroException extends Exception {
public DivisionByZeroException(String message) {
super(message);
}
}
public class CustomExceptionDemo {
static double divide(int numerator, int denominator) throws
DivisionByZeroException {
if (denominator == 0) {
throw new DivisionByZeroException("Cannot divide by zero");
}
return (double)numerator/denominator;
}
public static void main(String[]args) {
int numerator = 10;
int denominator = 20;
try {
double result = divide(numerator, denominator);
[Link]("Result of division : " + result);
}
catch(DivisionByZeroException e) {
[Link]("Exception caught : "+[Link]());
}
finally {
[Link]("Finally block executed");
}
}
}
9. Write a program to illustrate for nested try statements.
// Program to illustrate nested try statements in Java
public class NestedTryExample {
public static void main(String[] args) {
int[] numbers = {10, 20, 30};
try { // Outer try block
int result = numbers[1]; // This will throw ArrayIndexOutOfBoundsException
[Link]("Accessed element: " + result);
try { // Another inner try block
int division = 10 / 0; // This will throw ArithmeticException
[Link]("Division result: " + division);
} catch (ArithmeticException e) {
[Link]("Inner catch: Division by zero!");
}
} catch (ArrayIndexOutOfBoundsException e) {
[Link]("Inner catch: Array index out of bounds!");
}
[Link]("Program continues after nested try-catch blocks.");
}
}
10. Enlist any three java Built-in exception and explain.
Three common built-in exceptions in Java are
ArithmeticException - Thrown when an illegal arithmetic operation occurs.
Example: Dividing a number by zero.
ArrayIndexOutOfBoundsException - Raised when trying to access an array element with
an invalid index.
Example: Accessing index 5 in an array of size 3.
NullPointerException - Occurs when trying to use an object reference that points to null.
Example: Calling a method on a null object.
11. What is chained exception? Give an example that illustrates the mechanics of handling
chained exceptions.
Or
Write a Java program to create chained exceptions with top-level exception is Null
Pointer Exception and its causes Arithmetic Exception.
Chained exception is associating one exception with another exception. Cause of first
exception is second exception.
Following constructors and methods are used to allow chained exception in Java –
Throwable(Throwable causeEx);
Throwable(String msg, Throwable causeExc);
getCause()
initCause(Throwable causeExc);
class ChainExcDemo {
static void demoproc() {
NullPointerException e = new NullPointerException("top layer");
[Link](new ArithmeticException("cause"));
throw e;
}
public static void main(String args[]){
try {
demoproc();
}
catch (NullPointerException e) {
[Link]("Caught : " + e);
[Link]("Cause : " + [Link]());
}
}
12. Give the general form of an exception handling block and write a Java program to
illustrate multiple catch classes.
public class MultipleCatch {
public static void main(String[] args) {
// Outer try block
try {
int[] numbers = {10, 20, 30};
int result = numbers[1]; // ArrayIndexOutOfBoundsException
[Link]("Accessed element: " + result);
int division = 10 / 0; // ArithmeticException
[Link]("Division result: " + division);
} catch (ArrayIndexOutOfBoundsException e) {
[Link]("Array index out of bounds!");
} catch (ArithmeticException e) {
[Link]("Division by zero!");
} catch (Exception e) {
[Link]("General exception");
}
[Link]("Program ends.");
}
}
13. Write a custom exception in Java called “less marks” and raise this exception when marks
entered by valuator in the range [30-34].
import [Link].*;
class LessMarksException extends Exception {
LessMarksException(String msg) {
super(msg);
}
}
class CustomExceptionExample {
public static void main(String[] args)
{
Scanner sc = new Scanner([Link]);
try {
[Link]("Enter marks ");
int marks = [Link]();
[Link]("Marks entered " + marks);
if (marks >= 30 && marks < 35)
throw new LessMarksException("Less Marks 30-34");
}
catch (Exception e) {
[Link](e);
}
}
}
14. Build a Java program for a banking application to throw an exception, where a person
tries to withdraw the amount even though he/she has lesser than minimum balance
(Create custom exception)
import [Link].*;
class LowBalanceException extends Exception {
LowBalanceException(String msg) {
super(msg);
}
}
class Account {
private int balance;
Account(int balance) {
[Link] = balance;
}
public int getBalance() {
return balance;
}
public void withdraw(int amt) throws LowBalanceException{
if (balance - amt < 1000) {
throw new LowBalanceException("Minimum Balance Exception:
Cannot withdraw");
}
balance -= amt;
return;
}
class CustomExceptionExample1 {
public static void main(String[] args)
{
Scanner sc = new Scanner([Link]);
Account obj = new Account(10000);
try {
[Link]("Enter withdrawal amt ");
int amt = [Link]();
[Link](amt);
[Link]("Current Balance : " + [Link]());
}
catch (Exception e) {
[Link](e);
}
}
}
15. Develop a Java Program to create custom exception for Negative odd numbers.
// Custom Exception class
class NegativeOddException extends Exception {
public NegativeOddException(String msg) {
super(msg);
}
}
public class SimpleCustomException {
public static void main(String[] args) {
int num = -5; // test number
try {
if (num < 0 && num % 2 != 0) {
throw new NegativeOddException("Negative odd number: " + num);
}
[Link]("Number is valid: " + num);
} catch (NegativeOddException e) {
[Link]("Caught Exception: " + [Link]());
}
}
}
Lab Programs:
1. Develop a JAVA program to raise a custom exception (user defined exception) for DivisionByZero
using try, catch, throw and finally.
2. Develop a JAVA program to create a package named mypack and import & implement it in a
suitable class.
3. Create a package "vehicle" containing a class Car with a method showSpeed() that prints the
speed of the car. Import this package in another program and call the method.