0% found this document useful (0 votes)
11 views49 pages

Document

The document discusses various concepts related to Java programming, including class declaration, modifiers, input handling, constructors, method overriding, and inheritance. It provides detailed explanations and code examples for each topic, highlighting key features such as the use of 'this' and 'super' keywords, access specifiers, and the significance of the 'new' keyword. Additionally, it addresses common errors and misconceptions in Java, such as illegal method overriding and dynamic method dispatch.

Uploaded by

Shafi Esa
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views49 pages

Document

The document discusses various concepts related to Java programming, including class declaration, modifiers, input handling, constructors, method overriding, and inheritance. It provides detailed explanations and code examples for each topic, highlighting key features such as the use of 'this' and 'super' keywords, access specifiers, and the significance of the 'new' keyword. Additionally, it addresses common errors and misconceptions in Java, such as illegal method overriding and dynamic method dispatch.

Uploaded by

Shafi Esa
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 49

1.

Question: What are the possible ways of


declaring a Java class, and what are the key
components involved in its declaration?
• Detailed Concept Solution:
o Declaration: A Java class is declared
using the class keyword followed by a
valid class name.
o Modifiers (Optional): Access modifiers
(public, default), non-access modifiers
(abstract, final, strictfp).
▪ public: Class is accessible from
anywhere.
▪ default (no keyword): Class is
accessible only within the package.
▪ abstract: Class cannot be instantiated
directly, designed as a base.
▪ final: Class cannot be extended
(subclassed).
▪ strictfp: Class follows strict float
point calculations rules.
o Class Name: Must start with a letter, _,
or $; follows PascalCase convention
(e.g., MyClass).
o Body: Enclosed in curly braces {}
containing fields, methods, constructors,
inner classes.
o Example: public abstract class
MyAbstractClass { ... }
2. Question: Which modifiers are not allowed when
declaring an instance variable? Explain why.
• Detailed Concept Solution:
o abstract: Not allowed for instance
variables. abstract signifies a need for
subclasses to provide an implementation
(method, class), which doesn't apply to
individual object data storage (variable).
Instance variables are data components
that store a state, but abstract variables
don't fit in that context.
o strictfp: Not allowed. strictfp is used to
ensure that floating-point calculations
are consistent across different platforms,
it doesn’t make sense to have this
modifier at variable level and it’s only
applicable for classes and methods.
3. Question: Explain with a code sample how to
read input from a user in Java.
• Detailed Concept Solution:
o Scanner Class: Import java.util.Scanner
to use the scanner class.
o Create Scanner Object: Scanner
scanner = new Scanner(System.in);
associates the scanner with the standard
input.
o Read Input: Use methods like
nextLine(), nextInt(), nextDouble() to
read data as String, integer, or double.
o Close Scanner: Use scanner.close() to
release resources (best practice).
o Example:
o import
java.util.Scanner;
o public class UserInput {
o public static void
main(String[] args) {
o Scanner scanner = new
Scanner(System.in);
o

System.out.print("Enter
your name: ");
o String name =
scanner.nextLine();
o

System.out.print("Enter
your age: ");
o int age =
scanner.nextInt();
o

System.out.println("Hello,
" + name + "! You are " +
age + " years old.");
o scanner.close();
o }
o }
4. Question: Consider the following code snippet:
static void main(String
argument[]) {
System.out.println("This gets
printed"); }

What will be the output when this code is compiled


and executed? Explain your reasoning.
• Detailed Concept Solution:
o Error: The code will fail to compile
because it lacks a class definition which
is the basis of code execution in Java.
o Reasoning: The main method needs to
be within a valid class. Without the
enclosing class, the compiler cannot
resolve where to start the program
execution.
To make the program compile you need
to enclose the code under class as class
Main { static void main(String
argument[]) { System.out.println("This
gets printed"); } }
5. Question: What happens behind the scenes if a
constructor is not explicitly specified in a Java
class?
• Detailed Concept Solution:
o Default Constructor: If no constructor
is explicitly defined, the Java compiler
will generate an implicit default
constructor.
o Characteristics: The generated
constructor is a zero-argument
constructor, has the same access
modifier as the class, and has an empty
body (does nothing).
o Purpose: Allows object creation without
explicit initialization when no specific
initialization is required.
6. Question: What are the possible access specifiers
for a constructor in Java?
• Detailed Concept Solution:
o public: The constructor can be accessed
from any class. This means objects of
this class can be instantiated from
anywhere.
o private: The constructor can only be
accessed within the same class and used
to restrict the object creation from
outside the class, which is mostly used to
implement the singleton pattern.
o protected: The constructor is accessible
from within the same package and also
from any subclasses (even those that are
in different packages).
o default (no keyword): The constructor
is accessible only from within the same
package.
7. Question: What will be the output of the
following code snippet?
public class MyClass {
public void callMe(int a) {
System.out.println("Call
me with int argument");
}
public void callMe(long a) {
System.out.println("Call
me with long argument");
}
public static void main(String
args[]) {
MyClass myClassObj = new
MyClass();
int i = 6;
myClassObj.callMe(i);
}
}

• Detailed Concept Solution:


o Output: "Call me with int argument"
o Reasoning: Method overloading occurs
due to the existence of multiple methods
of same name but different parameters.
o Java selects the method that best
matches the argument types at compile
time. Since i is an int, it calls callMe(int
a).
8. Question: How would you define a constructor
in Java? Give an example.
• Detailed Concept Solution:
o Definition: A constructor is a special
method with the same name as the class
and no return type (not even void).
o Purpose: Used to initialize objects.
o Example:
o public class Dog {
o String breed;
o String name;
o int age;
o

o public Dog(String breed,


String name, int age) {
o this.breed = breed;
// Initializing the object
data fields
o this.name = name;
o this.age = age;
o }
o

o public Dog(){
o this.breed = "Lab";
o this.name = "Dog";
o this.age = 0;
o }
o }

9. Question: Explain the use of the this keyword in


Java, and provide a code sample demonstrating
its usage.
• Detailed Concept Solution:
o Meaning: this is a reference to the
current object in the context of a class.
o Use Cases:
▪ Resolving Naming Conflicts: When
constructor or method parameters
have the same name as instance
variables. this.variable = variable;.
▪ Constructor Chaining: Calling one
constructor from another in the same
class this(args).
▪ Passing Current Object: Passing
the current object to other methods.
o Example:
o public class Rectangle
{
o int width, height;
o public Rectangle (int
width, int height) {
o this.width = width;
o this.height = height;
o }
o public Rectangle(int size)
{ this(size,size); }
o public Rectangle
getCurrentRectangle(){
return this; }
o }

10. Question: Explain the key differences between


a class and an object in Java.
• Detailed Concept Solution:
o Class:
▪ A blueprint or template used to
create objects.
▪ A user-defined data type.
▪ A logical construct and compile-time
concept.
▪ Defines the structure (data) and
behavior (methods) of objects.
▪ No memory allocation upon
definition.
o Object:
▪ A specific instance of a class
(created using the new keyword).
▪ Represents a real-world entity or
concept in a program.
▪ Physical entity and run-time concept.
▪ Has its own copy of instance
variables.
▪ Memory allocated upon creation.
o Analogy: Class: Cookie Cutter; Object:
Cookie created by the cutter.
11. Question: Explain the role of the new keyword
in Java with a code sample.
• Detailed Concept Solution:
o Purpose: The new keyword is used to
create new objects (instances) of a class.
o Mechanism:
▪ Allocates memory on the heap for
the new object.
▪ Calls the constructor of the class to
initialize the new object.
▪ Returns a reference (memory
address) to the newly created object.
o Example:
o public class Book {
o String title;
o public Book(String
title) {
o this.title = title;
o }
o public static void
main(String[] args) {
o Book book1 = new
Book("Java Basics"); //
Creating a new Book object
o Book book2 = new
Book("OOP Concepts");
o }
o }

12. Question: Give an example of illegal method


overriding in Java and explain why it's illegal.
• Detailed Concept Solution:
o Illegal Scenario: Reducing the
accessibility of an overridden method in
subclass, changing return type, throwing
broader exception, overriding a static
method, overriding final method.
o Example:
• class Base {
• protected void display()
{}
• }
• class Sub extends Base {
• // Compile Time Error :
Illegal override (private is
lower accessibility than
protected)
• // private void
display(){}
• }

o Reasoning: Overriding must maintain or


increase the visibility to enable usage at
runtime, you can not reduce accessibility
of method while overriding, also you
cannot override static or final method,
because that will not satisfy inheritance
property.
13. Question: Explain the purpose and usage of the
super keyword in Java.
• Detailed Concept Solution:
o Meaning: super refers to the superclass
(parent class) of the current object.
o Use Cases:
▪ Accessing Superclass Members:
Accessing parent's methods or
variables when they have the same
name as those of the subclass, or
when they are hidden.
▪ Calling Superclass Constructor:
Explicitly calling a particular
constructor of the superclass,
super(arg).
o Example:
o class Animal {
o String name;
o public Animal(String
name) { this.name = name; }
o public void makeSound()
{
System.out.println("Generic
sound"); }
o }
o class Dog extends Animal {
o public Dog(String name)
{ super(name); }
o @Override
o public void makeSound()
{ super.makeSound();
System.out.println("Woof");
}
o }

14. Question: Identify the error in the code snippet


below and state the reason:
class Electronics { public
void displayPrice() {} }
class Camera extends Electronics {
public void displayname() {} }
class TestElectronics { public
static void main(String
argument[]) {
Electronics e = new Camera();
//Line 1
Camera c = new Electronics();
//Line 2
}
}

• Detailed Concept Solution:


o Error: Line 2 (Camera c = new
Electronics();) causes a compile-time
error.
o Reason: Assigning a superclass (parent)
object reference to a subclass (child)
reference without casting is not possible
because parent class object will not
contain methods/properties that exist in
child class. This is an illegal type
casting. However, child class object can
be assigned to a superclass reference
because every child object contains
properties and methods of the parent
class and it's the basis of inheritance
relationship.
15. Question: Write a code sample that
demonstrates how inheritance can help in code
reuse in Java.
• Detailed Concept Solution:
o Principle: Subclasses inherit members
(fields and methods) from superclasses
which avoids code duplication and
promotes maintainability.
o Example:
o class Shape {
o String color;
o public Shape(String color)
{ this.color = color; }
o}

o class Circle extends Shape {

o double radius;
o public Circle(String
color, double radius) {
o super(color);
o this.radius = radius;
o }
o}

o class Rectangle extends


Shape {
o double width;
o double height;
o public Rectangle(String
color, double width, double
height) {
o super(color);
o this.width = width;
o this.height =
height;
o }
o }

16. Question: Write a Java code sample that


demonstrates method overriding.
• Detailed Concept Solution:
o Concept: A subclass provides its own
implementation for a method inherited
from its superclass.
o Mechanism: Java uses dynamic method
dispatch (runtime polymorphism) to
determine the correct version of the
method during runtime based on the
object type.
o Example:
o

• class Vehicle { public void start() {


System.out.println("Vehicle started"); } }
class Car extends Vehicle {
@Override
public void start() { System.out.println("Car
started with key"); }
}
public class Main {
public static void main(String args[]) {
Vehicle vehicle = new Vehicle();
Car car = new Car();
vehicle.start(); // Calls the superclass method
car.start(); // Calls the overridden subclass
method
}
}
```
17. Question: Explain the function of the extends
keyword in Java with a code sample.
• Detailed Concept Solution:
o Purpose: The extends keyword is used
to declare that a class inherits from
another class (single inheritance in Java).
o Syntax: class Subclass extends
Superclass { ... }
o Example:
o class Animal {
o String name;
o public Animal (String
name){ this.name = name; }
o public void eat() {
System.out.println("Animal
is eating");}
o}

o class Dog extends Animal {


o public Dog (String name){
super(name); }
o public void bark() {
System.out.println("Dog is
barking");}
o }
18. Question: What will be the output of the
following code? Explain.
public class Animal {
public static void
saySomething() {
System.out.println("I am an
animal"); }
}
public class Dog extends Animal {
public static void
saySomething() {
System.out.println("I am a
dog"); }
public static void main(String
args[]) {
Animal a = new Animal();
a.saySomething();
Animal b = new Dog();
b.saySomething();
Dog d = new Dog();
d.saySomething();
}
}
• Detailed Concept Solution:
o Output:
o I am an animal
o I am an animal

o I am a dog

o Reasoning: Static methods are


associated with the class itself not with
the object and are resolved at compile
time. Hence, they are hidden in the
subclass when subclass implements a
static method with the same signature.
▪ a.saySomething(); calls
saySomething() of Animal class, as it
is an object of Animal class.
▪ b.saySomething(); also calls the
saySomething() from the Animal
class because the reference type of b
is Animal.
▪ d.saySomething(); calls the
saySomething() of Dog class, as it is
object of Dog.
19. Question: What is dynamic method dispatch
and why is it important in Java?
• Detailed Concept Solution:
o Definition: Dynamic method dispatch is
the mechanism where the method call to
an overridden method is resolved at
runtime based on the actual type of the
object (not reference type).
o Purpose: Supports polymorphism
(ability of objects of different classes to
respond to the same method call in their
own way), enabling the correct method
to be called at runtime based on the
object type not the reference type.
o Example:
o class Shape {
o public void draw() {
System.out.println("Drawing
a shape"); }
o }
o class Circle extends Shape {
o @Override
o public void draw() {
System.out.println("Drawing
a circle"); }
o }
o public class Main {
o public static void
main(String args[]) {
o Shape shape = new
Circle(); // shape is
reference variable of super
class type but object is of
sub class type
o shape.draw(); //
method will be called based
on object not the reference
type.
o }
o }

20. Question: Explain why Java does not support


multiple inheritance of classes.
• Detailed Concept Solution:
o Diamond Problem: Multiple
inheritance creates a diamond problem
or "Deadly Diamond of Death" where a
subclass inherits from multiple classes
that have the same method, the compiler
does not know which parent class
method to call and that creates an
ambiguity which causes compile time
error.
o Ambiguity: Java avoids this by allowing
only single inheritance of classes.
Multiple inheritance is achieved via
interfaces, which only specifies a
contract without implementation to
eliminate such issues.
21. Question: Explain how to prevent a method
from being overridden using a code sample.
• Detailed Concept Solution:
o final keyword: Mark method as final, it
cannot be overridden by the child class.
o private keyword: Mark method as
private making it not accessible to child
class, hence it cannot be overridden.
o Example:
o class Parent {
o public final void
myMethod() {
o

System.out.println("This is
a final method");
o }
o private void
myMethod2(){}
o }
o class Child extends Parent
{
o // Compile-Time Error:
Cannot override a final
method
o //public void
myMethod() { }
o // Compile Time Error:
cannot access private
method
o // public void
myMethod2(){}
o }

22. Question: Identify the error in the code and


state how it can be fixed:
public class Base {
public void doSomething() {
System.out.println("Doing
something in Base"); }
}
public class Sub extends Base {
private void doSomething() {
System.out.println("Doing
something in Sub"); }
}
• Detailed Concept Solution:
o Error: The doSomething() method in
the Sub class has a private modifier, it is
not a valid override because private
method is not visible to child class.
o Reason: An overriding method cannot
have a more restrictive access modifier
than the method in superclass.
o Fix: Change the access modifier of the
doSomething() method in the Sub class
to public or protected or default.
• public class Sub
extends Base {
• @Override
• public void doSomething()
{ System.out.println("Doing
something in Sub"); }
• }
23. Question: What are the possible ways of
declaring an interface in Java?
• Detailed Concept Solution:
o interface keyword: Use the keyword
interface followed by the interface name.
o Modifiers (Optional): public or default
(package-private).
▪ public: Accessible from anywhere.
▪ default: Accessible within the
package.
o Body: Contains only abstract method
declarations (implicitly public abstract)
and constant declarations (implicitly
public static final).
o Example:
• public interface
Drawable {
• void draw();
• int MAX_PIXELS = 1000;
• }
24. Question: Explain abstract classes in Java and
provide a code sample.
• Detailed Concept Solution:
o Definition: An abstract class cannot be
instantiated directly, and serves as a base
class for subclasses.
o abstract Keyword: The class is
declared with the abstract keyword.
o Abstract Methods: Contains methods
declared without implementation using
the abstract keyword, these must be
implemented in subclasses.
o Concrete Methods: Can also contain
regular methods with implementation.
o Purpose: To define a shared base class
for a group of related classes and enforce
that some methods must be implemented
by subclasses.
o Example:
```java
abstract class Shape {
String color;
public Shape(String color){ this.color =
color; }
public abstract double calculateArea();
public String getColor(){ return color;}
}
class Circle extends Shape {
double radius;
public Circle(String color, double
radius){
super(color);
this.radius = radius;
}
@Override
public double calculateArea() {
return Math.PI * radius * radius;
}
}
• ```

25. Question: Explain with a code sample how to


implement an interface in Java.
• Detailed Concept Solution:
o implements Keyword: A class
implements an interface using the
implements keyword.
o Requirement: Must provide an
implementation (method body) for all
the abstract methods declared in the
interface.
o Example:
o interface Drawable {
o void draw();
o }
o class Circle implements

Drawable{
o @Override
o public void draw(){
o

System.out.println("Drawing
circle");
o }
o }
26. Question: Is the following code snippet valid?
Explain your answer.
public abstract class
MyAbstractClass {
public void doSomething() {
//doing something }
public static void main(String
args[]) {
MyAbstractClass obj = new
MyAbstractClass();//Line 1
obj.doSomething(); //Line
2
}
}

• Detailed Concept Solution:


o Invalid: The code is invalid and will
produce a compilation error.
o Reason: Abstract classes cannot be
instantiated directly using the new
keyword at line 1 because they are
intended to be base classes and only
their child classes can be instantiated.
27. Question: Can a class implement two interfaces
in Java? What happens if both interfaces have a
method with the same name and signature?
• Detailed Concept Solution:
o Yes: A class can implement any number
of interfaces.
o Same Method Name: If both interfaces
declare methods with the same name and
signature, the class provides a single
implementation for that method which
will satisfy the contract for both
interfaces.
o Analogy It is like single method serving
the contract of two interfaces.
o Example
• interface A {
• void doSomething();
• }
• interface B {
• void doSomething();
• }
• class MyClass implements
A,B{
• @Override
• public void
doSomething() {

System.out.println("Doing
something");
• }
• }

28. Question: What is the primary use of abstract


classes in Java?
• Detailed Concept Solution:
o Base: To serve as a base class for a
hierarchy of related classes.
o Structure: To provide a common
structure for subclasses which can be
inherited and extended further.
o Abstraction: To provide partial code
implementation and abstract methods to
be implemented by subclasses.
o Code reuse: To enable reuse of code
and to prevent code redundancy.
29. Question: Explain the issue with the following
code snippet:
java public abstract final class MyAbstractClass
{ public void doSomething() { } }
• Detailed Concept Solution:
o Issue: The use of both abstract and final
modifiers together on a class definition
is illegal.
o Reason: An abstract class is meant to be
extended by other classes, while a final
class cannot be extended. These are
contradictory modifiers.
30. Question: Is the following code valid? Explain
why.
public interface ShapeDrawer
{ public void draw(); }
public class Triangle implements
ShapeDrawer {
public void draw () { // code
to draw shape }
public static void main(String
args[]) {
ShapeDrawer shapeDrawer =
new Triangle(); //Line 1
shapeDrawer.draw(); //Line
2
}
}

• Detailed Concept Solution:


o Valid: The code snippet is valid.
o Reason:
▪ Triangle class correctly implements
the ShapeDrawer interface.
▪ The draw() method of Triangle
implements the draw() method
defined in the ShapeDrawer
interface.
▪ An interface reference (ShapeDrawer
shapeDrawer) can hold a reference to
an object of a class which
implements the interface. This is a
good example of runtime
polymorphism.
31. Question: Which lines in the following code
snippet will cause a compilation error?
public interface MyInterface
{
private static int FIELD1 = 7;
//Line 1
int FIELD2 = 8; //Line 2
public final int FIELD3;
//Line 3
public static int FIELD4 = 8;
//Line 4
}

• Detailed Concept Solution:


o Line 1: private static int FIELD1 = 7;
will cause compilation error because
interface members cannot be private.
Interface members are implicitly public.
o Line 3: public final int FIELD3; will
cause compilation error because final
fields must be initialized during
declaration. Interface fields are
implicitly static final and hence must be
initialized during declaration.
o Line 2 and 4 are valid lines because
interface fields are implicitly public
static and final.
o Reason: Interface fields must be public,
static, and final and must be initialized
during declaration.
32. Question: Is the code snippet below valid?
Explain.
public abstract class
MyAbstractClass {
private abstract void
doSomething();
}
• Detailed Concept Solution:
o Invalid: This code snippet is invalid and
will produce a compile-time error.
o Reason: private abstract modifiers are
not allowed together on a method
definition. Private methods cannot be
overridden by subclasses, whereas
abstract methods are meant to be
implemented by subclasses so private
abstract method definition is a
contradiction.
33. Question: Explain with a code sample how to
create a package in Java.
• Detailed Concept Solution:
o package Keyword: Use the package
keyword at the top of a Java file
followed by the package name which
can be a dot-separated hierarchy.
o File Structure: The directory structure
of the source files must match the
package name. (e.g.
com.example.mycode would mean
src/com/example/mycode folder where
the source file must reside).
o Example:
o // File:
src/com/example/MyClass.jav
a
o package com.example;

o public class MyClass {

o}

34. Question: Name some default packages in the


JDK and briefly explain what they do.
• Detailed Concept Solution:
o java.lang: Core classes of Java (Object,
String, Math, Thread). Automatically
imported.
o java.util: Utility classes (Collections,
Scanner, Random, Date).
o java.io: Input/output operations,
including file handling.
o java.net: Networking classes for sockets
and URLs.
o java.awt, javax.swing: Classes for
creating GUIs.
35. Question: Explain the differences between the
protected and default (package-private) access
specifiers in Java.
• Detailed Concept Solution:
o protected: Members are visible within
the same package and also in subclasses
(even if subclasses are in a different
package).
o default (package-private): Members
are visible only within the same
package.
o Subclass: protected variables are
accessible in child classes which are in
different packages and default variables
are not accessible from child classes in
different packages.
36. Question: Explain the purpose and significance
of the java.lang package in Java.
• Detailed Concept Solution:
o Core Package: Contains the
fundamental classes of the Java
language.
o Automatic Import: Implicitly imported
into every Java program (no need to
explicitly use import java.lang.*;).
o Key Classes: Object, String, Math,
wrapper classes (Integer, Double),
Thread etc.
o Foundation: Provides the base classes
and interfaces for all Java programs.
37. Question: Explain what happens when the
following code is compiled and executed:
// File:
com/questions/CoreJava.java
package com.questions;
public class CoreJava {
private String getQuestion() {
return "Question1"; }
}
// File: com/questions/JSP.java
package com.questions;
class JSP extends CoreJava {
public void getJSPQuestion() {
System.out.println(getQuestion()
); }
}

• Detailed Concept Solution:


o Error: The program will produce a
compile-time error.
o Reason: The getQuestion() method is
private in the CoreJava class so it cannot
be accessed by subclasses from outside
class.
38. Question: What will be the output when you
compile and execute the following code?
class Test {
try {
System.out.println("This is
try block");
}
System.out.println("Try block is
executed"); //Line 1
catch(Exception exp) {
System.out.println("This is
catch block");
}
}

• Detailed Concept Solution:


o Error: This code will not compile.
o Reasoning: It is mandatory to have
curly braces around the code in the try
block, so the System.out.println("Try
block is executed"); is not part of the try
block. The program needs a finally block
or at least one catch block to be present
after the try block.
39. Question: What will be the output of the
following code snippet?
class ExceptionTest {
public static void main(String
argument[]) {
callMethod();
}
static void callMethod() {
int intValue = 100 / 0;

System.out.println("intValue is:
" + intValue);
}
}

• Detailed Concept Solution:


o Error: The program will throw
ArithmeticException at runtime due to
division by zero.
o Reason: The callMethod calculates
value of 100/0 which throws unchecked
exception. Because this exception is not
handled, the program will terminate
abruptly.
40. Question: Explain the try-catch-finally block in
Java's exception handling mechanism.
• Detailed Concept Solution:
o try Block: Encloses code that might
throw an exception. The try block
monitors this code for any potential
exceptions.
o catch Block: Follows a try block and
handles a specific type of exception if
one occurs in the try block.
o finally Block: Optional block that
always executes after the try and catch
blocks, whether or not an exception is
thrown. Used for cleanup (e.g., closing
resources).
o Purpose: To handle exceptions
gracefully, preventing program crashes,
allowing recovery if possible, and
ensuring resources are released.

You might also like