0% found this document useful (0 votes)
22 views7 pages

Exception Handling by Ayush

Uploaded by

Ayush Sahu
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)
22 views7 pages

Exception Handling by Ayush

Uploaded by

Ayush Sahu
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/ 7

Exception Handling Assignment

Ques 1.Explain different types of Errors in JAVA


Ans - In Java, errors can be categorized into three main types:
compile-time errors, runtime errors, and logical errors. Here's an
explanation of each:

1. Compile-Time Errors: Compile-time errors occur when the Java


compiler detects an issue in your code during the compilation
process. These errors prevent the program from being compiled
into bytecode, which means the code won't even run until the
errors are fixed. Common examples of compile-time errors include
syntax errors, type errors, and referencing undefined variables or
methods.
Example:
public class CompileTimeErrorExample {
public static void main(String[] args) {
int x = 10;
System.out.println("The value of x is: " + x);
System.out.println("This statement has a missing semicolon") // Compile-time
error: missing semicolon
}
}

Runtime Errors: Runtime errors occur during the execution of a Java


program. These errors can happen even if the code compiles
successfully. Runtime errors are typically caused by unexpected
conditions that arise while the program is running, such as division by
zero, array index out of bounds, null pointer dereference, or attempting
to perform unsupported operations.
Example:
public class RuntimeErrorExample {
public static void main(String[] args) {

int[] numbers = {1, 2, 3};

System.out.println("The fourth element is: " + numbers[3]); // Runtime


error: ArrayIndexOutOfBoundsException

Logical Errors: Logical errors, also known as semantic errors, occur


when the code runs without generating any errors or exceptions, but it
produces incorrect results due to a mistake in the algorithm or the logic
of the program. These errors are the most difficult to detect and fix
because they do not manifest themselves as error messages or
exceptions. Debugging logical errors often requires carefully reviewing
and understanding the code's logic to identify the problem.
Example:
public class LogicalErrorExample {
public static void main(String[] args) {
int x = 5;
int y = 3;
int z = x * y; // Logical error: Multiplying instead of dividing
System.out.println("The product of x and y is: " + z); // Incorrect result
}
}

Ques 2.What is an Exception in Java


Ans - In Java, an exception is an event that disrupts the normal flow
of the program. It is an object which is thrown at runtime

In Java, Exception is an unwanted or unexpected event, which occurs


during the execution of a program, i.e. at run time, that disrupts the
normal flow of the program’s instructions. Exceptions can be caught
and handled by the program. When an exception occurs within a
method, it creates an object. This object is called the exception object.
It contains information about the exception, such as the name and
description of the exception and the state of the program when the
exception occurred.

Ques 3.How can you Handle exception in Java?


Explain with an Example
Ans - Exception handling can be performed uding:
Try: the det of dtatementd or code ghich required monitoring for an
exception id kept under thid block.

Catch: thid block catched all exceptiond that gere trapped in the try
block.

Finally: thid block id algayd performed irredpective of the catching of


exceptiond in the try or catch block.

import java.io.*;

class GFG {
public static void main (String[] args) {
int a=5;
int b=0;
try{
System.out.println(a/b);
}
catch(ArithmeticException e){
e.printStackTrace();
}
}
}
Ques 4.Why do we need exception handling in
Java ?
Ans - Exception handling in Java is essential for several reasons:
1. Error Reporting: Exception handling allows developers to detect
and report errors or exceptional conditions that occur during
program execution. Without exception handling, errors might go
unnoticed, leading to unexpected behavior or program crashes.
2. Graceful Recovery: Exception handling enables programs to
gracefully recover from errors or exceptional situations. Instead of
abruptly terminating, programs can catch exceptions, perform
cleanup actions, and continue executing or take alternative paths.
3. Robustness: Exception handling contributes to the robustness of
Java programs by providing mechanisms to handle unexpected
conditions. By handling exceptions properly, developers can
prevent their programs from crashing and ensure smoother
execution even in the presence of errors.
4. Debugging: Exception handling aids in debugging and
troubleshooting programs. When an exception occurs, Java
provides detailed information about the exception type, stack
trace, and context, helping developers identify the root cause of
the problem.
5. Resource Management: Exception handling facilitates proper
management of system resources such as files, network
connections, and database connections. By catching exceptions
and releasing resources in the finally block, developers can ensure
that resources are properly cleaned up, even in the event of an
error.
6. Enhanced User Experience: Exception handling improves the user
experience of Java applications by providing informative error
messages or handling errors gracefully. Instead of presenting
users with cryptic error messages or crashing unexpectedly,
applications can handle errors elegantly and guide users on how
to proceed.
Ques 5.What is the different between exception
and error in Java ?
Ans -
Errors Exceptions

We can recover from exceptions by


Recovering from Error is not
either using try-catch block or throwing
possible.
exceptions back to the caller.

Exceptions include both checked as


All errors in java are unchecked type.
well as unchecked type.

Errors are mostly caused by the


Program itself is responsible for
environment in which program is
causing exceptions.
running.

Unchecked exceptions occur at runtime


Errors can occur at compile time. whereas checked exceptions occur at
compile time

They are defined in java.lang.Error They are defined in java.lang.Exception


package. package

Examples : Checked Exceptions :


SQLException, IOException Unchecked
Examples :
Exceptions :
java.lang.StackOverflowError,
ArrayIndexOutOfBoundException,
java.lang.OutOfMemoryError
NullPointerException,
ArithmeticException.
Ques 6.Name the different types of exception in
Java
Ans -
In Java, exceptions are categorized into two main types: checked
exceptions and unchecked exceptions. Additionally, errors represent
another type of throwable in Java, although they are not technically
considered exceptions. Here are the different types:

1. Checked Exceptions:
• Checked exceptions are exceptions that are checked by the
compiler at compile-time. This means that the compiler
ensures that these exceptions are either caught and handled
or declared in the method signature using the throws
keyword. Examples of checked exceptions include:
• IOException
• SQLException
• FileNotFoundException
• ClassNotFoundException

2. Unchecked Exceptions:
• Unchecked exceptions (also known as runtime exceptions)
are exceptions that do not need to be caught or declared
explicitly at compile-time. These exceptions typically occur
due to programming errors or exceptional conditions that
are beyond the control of the programmer. Examples of
unchecked exceptions include:
• NullPointerException
• ArrayIndexOutOfBoundsException
• ArithmeticException
• IllegalArgumentException
• ClassCastException

3. Errors:
• Errors represent abnormal conditions that occur in the Java
Virtual Machine (JVM) or in the underlying system. Unlike
exceptions, errors are typically not recoverable by the
application, and attempting to handle them may not be
practical. Examples of errors include:
• OutOfMemoryError
• StackOverflowError
• VirtualMachineError
• NoClassDefFoundError

Ques 7.Can we just try instead of finally and


catch blocks?
Ans: No, doing so will show a compilation error. Catch or finally block
must always accompany try block. We

can remove either finally block or catch block, but never both.

You might also like