[Go to site: main page, start]

0% found this document useful (0 votes)
17 views12 pages

Java Exception Handling Overview

The document provides a comprehensive overview of exception handling in Java, detailing the types of exceptions, their subclasses, and the rules for using try-catch-finally blocks. It explains the differences between the 'throw' and 'throws' keywords, as well as the distinction between checked and unchecked exceptions. Additionally, it covers the creation and use of custom exceptions to handle specific error scenarios more effectively.

Uploaded by

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

Java Exception Handling Overview

The document provides a comprehensive overview of exception handling in Java, detailing the types of exceptions, their subclasses, and the rules for using try-catch-finally blocks. It explains the differences between the 'throw' and 'throws' keywords, as well as the distinction between checked and unchecked exceptions. Additionally, it covers the creation and use of custom exceptions to handle specific error scenarios more effectively.

Uploaded by

mdsamadabdul28
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

=============== Exception Handling in Java==========================

- Exception is an event that occurs during the execution due to wrong


input and it leads to abnormal termination of program execution.

- Whenever an exception is raised, JVM creates an object of type


of Exception or sub type of Exception and then returns the exception
related message to the console.

- Exception is a predefined class available in java.


- Exception is a sub class of Throwable.
- Throwable is the super-most class for each Error and Exception and their
sub types.
- Error is a predefined class.
- Error has sub classes such as:
- AssertionError
- ThreadDeath
- VirtualMachineError
- LinkageError
*AssertionError thrown to indicate that an assertion has failed.
* It was introduced in java 1.4 version.

* ThreadDeath is thrown in the victim thread when the (deprecated) [Link]()


method is invoked.
-It was introduced in Java 1.0 version.
-An application should catch instances of this class only if it
must clean up after being terminated [Link]
ThreadDeath is caught by a method, it is important that it should
be re-thrown so that the thread actually dies.

*VirtualMachineError object is thrown to indicate that the Java Virtual Machine


is broken or has run out of resources necessary for it to continue operating.
- It has multiple sub classes:
a. InternalError:
Its object thrown is to indicate some unexpected internal error that
has occurred in the Java Virtual Machine.
b. StackOverflowError: It is thrown when a stack overflow occurs because
of an application recursing too deeply.
c. UnknownError:Thrown when an unknown but serious exception has occurred
in the Java Virtual Machine.
[Link]:It is thrown when the JVM cannot allocate an object
because it is out of memory, and no more memory could be made
available by the garbage collector.

* LinkageError: Its a subclass of Error.


Its subclasses indicate that a class has some dependency on another class;
however, the latter class incompatibly changed after the compilation
of the former class.
It has sub classes such as:
a. ClassFormatError
b. IncompatibleClassChangeError
c. ClassCirculatoryError
d. ExceptionInitializerError
e. VerifyError
f. UnsatisfiedLinkError
g. NoClassDefoundError
Some of the miscellaneous Error as sub class of IncompatibleClassChangeError
are: NoSuchFieldError,NoSuchMethodError,InstanitationError,
AbstractMethodError etc.
Note:
NoSuchFieldError is thrown if an application tries to access or modify a specified
field of an object, and that object no longer has that field.
Generally, this error is caught by the compiler; this error can
only occur at run time if the definition of a class has
incompatibly changed.

NoSuchMethodError: It is thrown if an application tries to call a specified method of a


class (either static or instance), and that class no longer has a
definition of that method.
Normally, this error is caught by the compiler; this error can
only occur at run time if the definition of a class has
incompatibly changed.

IllegalAccessError: It is thrown if an application attempts to access or modify


a field, or to call a method that it does not have access to.

---Exception class in java:


- Exception is a predefined class available in [Link] package.
- It is the sub class of Throwable.
- Exception and its subclasses indicates conditions that are reasonable for an
application might to catch.
- Exception has in general two categories of sub classes:
- Sub classes of RuntimeException
- Direct Sub classes of Exception

-Sub classes of Exception:


a. RunTimeException
b. ClassNotFoundException
c. NoSuchFieldException
d. NoSuchMethodException
e. InterruptedException
f. AccessorException
g. ActivationException
h. AlreadyBoundException
i. AnalyzerException
j. AWTEXception
k. BackingStoreException
l. BrokenBarrierException
m. CertificateException
n. CGIClientException
o. CompilerException
p. DataFomatException
q. DispatchException
r. DestroyFailedException
s. DuplicateException
t. ExceutionException
u. FilterException
v. IllegalClassFormatException
w. InvalidApplicationException
x. InvalidValueException
y. IOException
z. JAXBException
-------------
a. LambdaConversionException
b. LocaleSyntaxException
c. NamingException
d. NoSuchEventException
e. NoSuchProducerException
f. NoSuchRecordingException
g. NotBoundException
h. ParseException
i. PathException
[Link]
k. ReflectiveOperationException
l. ScriptException
m. ServerNotActiveException
n. ServerSideException
o. SOAPException
p. SQLException
q. TargetLostException
r. TimeOutException
s. WindowsException
t. XMLParseException
---------------------------------------------------------------------
Rules:
1. try with no catch, not allowed
2. catch without try not allowed
3. only finally not allowed
4. duplicate exceptions type in catch not allowed.
5. multiple finally block not allowed for one try
-----------------------------------------------------------------------

1. try catch finally -- allowed


2. try catch -- allowed
3. try finally ---allowed
4. single try multiple catch-- allowed
5. try catch catch finally -- allowed
6. try catch multiple finally -- not allowed
7. single try multiple catch with same type parameter---not allowed
8. try catch finally at class level--not allowed
9. return statement in finally---allowed (no further statement allowed
If return statement is in finally block inside if condition ,we don't get get CTE for
further statement after finally block
[Link] catch parameter of try catch in outer try and outer catch parameter
can be same type
[Link] catch parameter of try catch in outer catch and outer catch
parameter must not be same type
12. variable declared in try block can't be accessed in
catch block and finally block
13. variable declared in method can't be accessed inside try,catch as
well as finally in same method if its not initialized
in declaration level.
[Link] declared in method but initialized in try block
can't be accessed in other block.
Because statements inside try block may not get
executed as there may be exception at any
line of instruction in try block.
15. variable declared in method but initialized in try block
can't be accessed in other block.
But if re-initialized in catch block1 then no [Link] in
another catch block2 it can't be
accessed.
16. If variable is declared in method then it must be initialized
in each block where we want to access.
17. In real time, always initialize variable in method with
compatible value,then you will not get error while
accessing from try catch finally block.
Here we guarantee to compiler that x value is provided no
need to worry , access the value i.e, initialized.
========================================================================
===============
18. in a non-void method, return statement only in try block
will generate CTE.
value must be returned just before from end of method also.
19. in a non void method, return statement only in try block
will generate CTE.
value must be returned from catch block even if from
not returned just before end of method.
20. if there are multiple catch block and value not returned
from all the catch block
then there will be again [Link] make sure not to provide any statement after last catch
returning value,or else we will get [Link] you have to execute the statements later
then in this case you must provide statements in finally
block so that there will be no CTE.

========================================================================
=========
All about Throwable:
Point to remember:
---------------------------------------------------|
For any exception message, the format is : |
"Exception class name" + "reason of exception" |
"position of exception generated in code" |
--------------------------------------------------------|
The Throwable class in Java is the root class of all errors and exceptions in the
Java language. It provides methods for getting the stack trace, the cause of the
throwable, and the message.
Throwable has two direct subclasses:
Error and Exception.

Methods of Throwable class:


getMessage(): Returns the message of the throwable.
getStackTrace(): Returns an array of stack trace elements
representing the stack trace related to current
Throwable.
getCause(): Returns the cause of the throwable.
printStackTrace(): Prints this throwable and its backtrace to
the standard error stream.
addSuppressed(): Appends the specified exception to the list of exceptions that were
suppressed in order to deliver this exception.
fillInStackTrace(): Fills in the stack trace of this throwable.
initCause(): Initializes the cause of this throwable.
========================================================================
==============

throw:
It is a keyword.
It is used for throwing an exception from a method or constructor
based on conditions.
Only one exception can be thrown at a time using throw keyword.

Syntax:
throw new Throwable or any of its sub class object();
// use object directly or use its RV
For e.g:
whenever we use any login page we provide data as input,
background input is verified whether its avaialble in DB or not.
If not then system terminates the execution and we get Exception message on console.

By throwing an exception we are actually terminating the execution and passing


Readable instructions to user so that user will not be worried about the reason of
exception.

Points to remember:
- It must be used only inside a method,constructor,
- It can't throw multiple type of exception object at a time.
- If you have to throw multiple exception object then each throw exception object
statement must be placed in different conditional statement
- It can't be used at prototype level of method or constructor.
- It can't be used inside static block, instance block.
- AFTER throw exception object statement you must not provide any other statement,
if you have to execute other statement then put throw exception statement inside
Conditional statement.

throws:
It is a keyword.
It is used for informing the caller method about the exception.
throws keyword doesn't have any importance at execution time
Whether throws is used or not used JVM will send the exception to the calling method.
It can report multiple exceptions at a [Link] must place comma when we have to report
multiple exceptions.

Points to remember:
- It must be placed only after method parenthesis or constructor parenthesis.
- Its mandatory to be used for checked exceptions
- Its optional to be used for unchecked exceptions
- It is not allowed in static block , instance block or any other element
other than after method or constructor parenthesis
- We can use multiple exception types after throws by using comma between types.
- If a method in super class doesn't contain throws checked exception then
in sub class overridden method also we should not provide throws.

e.g:
public static void m1(int a) throws AE,SIOBE,AIOBE{
if()
throw new AE("message 1");
if()
throw new SIOBE("message 2");
if()
throw new AIOBE("message 3");
}

If a called method is throwing exception to caller then it must be caught by using


try catch in caller method.

Q. What is the difference between throw and throws?


Answer:
throw is used for throwing an exception manually by the developer based on conditions.
throws is used to report the exceptions thrown in called method to the caller method so
that the exception is handled in the caller method by using try catch block.

Only one exception object is allowed after throw keyword.


Multiple exceptions types are allowed after throws keyword.

When we use throw keyword, we must place exception object after it,
When we use throws keyword we must place exception class name after it.

throw must be used inside the body of method as part of logic.


throws must be used in method header after parameter list i.e., after '()'

throw keyword is generally used for throwing checked and customized exceptions.
throws keyword is used for reporting checked exceptions and it is mandatory.

Q. When shall we use throw, throws , try catch?


Answer: Whenever we have to develop a method which takes input from user
and based on any condition we have to use throw and throws for throwing
exception and report the exception to the caller respectively.

When we have to suppress exception and continue our program execution or


provide readable/understandable message to the user regarding the cause of
exception then we must use try catch.

------------------------------------------------------------------------------
========================================================================
=========
Types of Exceptions:
In Java, there are two types of exceptions: checked and unchecked.
Checked exceptions are exceptions that the compiler forces you to handle,
while unchecked exceptions are exceptions that you are not required to
handle.
Here are some examples of checked exceptions:
FileNotFoundException: - This exception is thrown when a file that
you are trying to access does not exist.
IOException: - This exception is thrown when an input or output
operation fails.
SQLException: - This exception is thrown when a database
operation fails.
Here are some examples of unchecked exceptions:
ArithmeticException: - This exception is thrown when an arithmetic
operation, such as division by zero, fails.
NullPointerException: - This exception is thrown when you try to access
a null object.
ArrayIndexOutOfBoundsException: - This exception is thrown when you
try to access an element of an array that is out of bounds.
You can tell if an exception is checked or unchecked by looking at its
superclass. If the superclass is Exception or one of its subclasses, then
the exception is checked. If the superclass is RuntimeException or one
of its subclasses, then the exception is unchecked.

It is generally considered good practice to handle checked exceptions,


even though you are not required to do so. This is because checked
exceptions are typically indicative of a problem with your code
that you should fix. Unchecked exceptions, on the other hand, are
typically indicative of a problem with the user input or the
environment in which your code is running.

Here are some tips for handling checked exceptions:


Use a try-catch block to catch the exception and handle it appropriately.
Re-throw the exception to the calling method.
Declare the exception in the throws clause of the method signature.
Here are some tips for handling unchecked exceptions:
Use a try-catch block to catch the exception and handle it appropriately.
Log the exception and continue running.
Ignore the exception.
It is important to note that there are some exceptions to the general
rules for handling checked and unchecked exceptions.
For example, the InterruptedException exception is a checked exception,
but it is often ignored because it is typically thrown when a thread
is interrupted.
Ultimately, the decision of whether or not to handle a checked exception
is up to you. However, it is important to be aware of the potential
consequences of not handling a checked exception.

--------------------Custom Exception--------------
A custom exception in Java is a class that extends the Exception class.
It is used to handle specific error scenarios in a more precise manner.
Custom exceptions are typically used to provide more detailed information
about the error, such as the cause of the error and the steps that can be
taken to resolve it.
To create a custom exception, you need to create a class that extends the
Exception class. The class should have a constructor that takes a String as
the error message. The class should also have methods to get the error
message and the cause of the error.
Here is an example of a custom exception:
public class CustomException extends Exception {

private String errorMessage;


private Throwable cause;

public CustomException(String errorMessage) {


super(errorMessage);
[Link] = errorMessage;
}

public CustomException(String errorMessage, Throwable cause) {


super(errorMessage, cause);
[Link] = errorMessage;
[Link] = cause;
}

public String getErrorMessage() {


return errorMessage;
}
public Throwable getCause() {
return cause;
}
}
Once you have created a custom exception, you can use it in your code by
throwing an instance of the exception. The following code shows how to
throw an instance of the CustomException class:

try {
// Code that may throw an exception
} catch (CustomException e) {
// Handle the exception
}
You can also use custom exceptions to catch specific error scenarios.
The following code shows how to catch an instance of the CustomException class:
Java

try {
// Code that may throw an exception
} catch (CustomException e) {
// Handle the exception
} catch (Exception e) {
// Handle other exceptions
}
Custom exceptions are a powerful tool that can be used to improve
the quality of your Java code. By using custom exceptions, you can
provide more detailed information about errors and handle specific
error scenarios in a more precise manner.
//Custom Exception Class
@SuppressWarnings("serial")
class InvalidTransactionException extends Exception {
public InvalidTransactionException(String message) {
super(message);
}
}

//Bank Account Class


class BankAccount {
private String accountNumber;
private double balance;

public BankAccount(String accountNumber, double initialBalance) {


[Link] = accountNumber;
[Link] = initialBalance;
}

public void deposit(double amount) {


balance += amount;
[Link]("Deposited: " + amount);
}

public void withdraw(double amount) throws InvalidTransactionException {


if (amount <= 0) {
throw new InvalidTransactionException("Invalid amount for withdrawal");
}
if (amount > balance) {
throw new InvalidTransactionException("Insufficient funds for withdrawal");
}
balance -= amount;
[Link]("Withdrawn: " + amount);
}

public double getBalance() {


return balance;
}
}

//Main Class to Demonstrate Bank Account Operations


public class BankDemo {
public static void main(String[] args) throws InterruptedException {
// Create a bank account with initial balance
BankAccount account = new BankAccount("123456789", 1000);

// Perform transactions
try {
[Link](500);
[Link]("Current Balance: " + [Link]());
[Link](5000);
[Link](200);
[Link]("Current Balance: " + [Link]());
[Link](5000);
[Link](1500); // This will throw an exception
[Link]("Current Balance: " + [Link]()); // This will not execute
} catch (InvalidTransactionException e) {
[Link](5000);
[Link]("Transaction Error: " + [Link]());
}
}
}

Common questions

Powered by AI

Best practices include using multiple `catch` blocks to handle different exception types separately, ensuring each block is specific to an exception type, and not catching overly broad or unrelated exceptions in a single block. It's also important to ensure resources are managed properly using `finally` or try-with-resources. Avoiding duplicate exception types within `catch` blocks prevents compile-time errors, and using `throws` intelligently at the method signature can help in managing checked exceptions effectively without cluttering method logic .

Checked exceptions, like `IOException` and `SQLException`, must be either caught or declared in the method signature with `throws`, as the compiler enforces handling to prompt developers to address potential errors. Unchecked exceptions, such as `NullPointerException` and `IndexOutOfBoundsException`, are not required to be caught or declared, as they usually indicate programming bugs or logical errors that developers should correct . Checked exceptions often derive from Exception, whereas unchecked exceptions derive from RuntimeException .

The `throw` keyword is used to explicitly throw an exception in the code based on certain conditions. It is followed by an exception object and is used within a method or constructor body. Conversely, the `throws` keyword declares that a method can throw exceptions and is used in the method signature to indicate the types of exceptions that may be thrown, allowing the caller to handle them appropriately. `throw` is used for checked and customized exceptions, while `throws` is mandatory for checked exceptions, providing a list of potential exceptions that may occur .

The `throws` keyword declares that a method can throw one or more exceptions, allowing the calling method to prepare for error handling using the `try-catch` construct. This is particularly useful in scenarios involving I/O operations, where a method performing file operations might declare `throws IOException`, informing the caller to handle potential read/write failures. In network operations, `throws SQLException` can ensure that database connection errors are managed externally, preventing hidden failures and encouraging robust error handling structures in applications .

Handling checked exceptions effectively involves using `try-catch` blocks to catch and manage exceptions, re-throwing exceptions to escalate error handling, or declaring exceptions using the `throws` clause in the method signature. It's considered good practice because these exceptions represent issues potentially within the code which should be addressed. For example, a `FileNotFoundException` should be handled by verifying file paths and providing a fallback or user notification . Handling exceptions properly ensures stability and more predictive outcomes in software .

Providing a return statement inside a `finally` block can lead to unexpected behavior, as it will override any return statement in the `try` or `catch` blocks, making it difficult to predict the method's final output. Although allowed, it's generally discouraged due to code readability and debugging complexity, as it can obscure the control flow and lead to logical errors . Ensuring that `finally` is primarily used for cleanup rather than altering method returns can mitigate risks associated with this practice.

The `Throwable` class is the root class for all exceptions and errors, providing critical methods for handling these situations in Java. It contains methods like `getMessage()`, which retrieves the error message of the exception; `getStackTrace()`, which provides an array of stack trace elements representing the stack trace at the point where the exception occurred; `getCause()`, which returns the cause of the throwable; `printStackTrace()`, which prints the throwable and its backtrace; and `fillInStackTrace()`, which fills in the stack trace of the current throwable . These methods help in diagnosing errors and exceptions effectively by offering detailed context and traceability.

Custom exceptions in Java are utilized to handle specific error scenarios more precisely by extending the Exception class. They provide detailed information about the error, such as the error message and cause. In a banking application, a custom exception can be created to handle invalid transactions, such as withdrawing a negative amount or attempting to withdraw more funds than available. For example, the `InvalidTransactionException` can be thrown with a descriptive message when such conditions occur during withdrawal operations, allowing the application to catch and respond to specific transaction errors accordingly .

The `try` block contains code that may throw an exception. The `catch` block follows `try` and catches exceptions thrown by the `try` block, allowing them to be handled. `finally` is used after `try` and `catch` blocks to execute code whether an exception is thrown or not, such as cleaning up resources. A `try` must be followed by one or both of `catch` and `finally`, and rules dictate that duplicate exception types in a `catch` or multiple `finally` blocks for a single `try` are not allowed .

Not handling checked exceptions in Java can lead to runtime errors, unpredictable application behavior, or program termination. For instance, failing to handle an `IOException` when reading a file could make the application crash if the file is inaccessible, thus negatively impacting user experience and system reliability. The Java compiler forces handling of checked exceptions to prevent such scenarios, making sure developers acknowledge and plan for potential issues .

You might also like