Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
41 views

Java Handling Abw

The document discusses various topics related to exception handling in Java including: 1. The runtime stack mechanism and how exceptions are handled by default if not caught. 2. The exception hierarchy with Exception and Error as top-level classes. Checked vs unchecked exceptions are also explained. 3. Using try-catch blocks to handle exceptions with control flow examples of what happens if exceptions are or aren't caught. 4. Methods to print exception information like printStackTrace(), toString(), and getMessage(). 5. Using multiple catch blocks to handle different exception types and the importance of order when doing so.

Uploaded by

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

Java Handling Abw

The document discusses various topics related to exception handling in Java including: 1. The runtime stack mechanism and how exceptions are handled by default if not caught. 2. The exception hierarchy with Exception and Error as top-level classes. Checked vs unchecked exceptions are also explained. 3. Using try-catch blocks to handle exceptions with control flow examples of what happens if exceptions are or aren't caught. 4. Methods to print exception information like printStackTrace(), toString(), and getMessage(). 5. Using multiple catch blocks to handle different exception types and the importance of order when doing so.

Uploaded by

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

Contents

1. Introduction
2. Runtime Stack Mechanism
3. Default exception handling in java
4. Exception hierarchy
5. Customized exception handling using Try and Catch block
6. Control flow in Try Catch
7. Methods to print exception information
8. Try with multiple Catch blocks
9. Finally Block
10. Difference between Final, Finally and Finalize
11. Various possible combinations of Try-Catch-Finally
12. Control flow in Try-Catch-Finally
13. Control flow in nested Try-Catch-Finally
14. Throw keyword
15. Throws keyword
16. Exception handling keyword summary
17. Various possible errors in exception handling in compile time
18. Customized or user defined exceptions
19. Top 10 Exceptions
20. 1.7 version enhancements
Try with resources
Multi-catch block
1. Introduction
An unwanted, unexpected event that disturbs the normal execution of the
program is called exception.
Exception Handling
Graceful termination of the program
If something goes wrong we should not miss anything, we should not lose
any resources, we should not block any resources and graceful termination
is required then we should go for the Exception handling.
To define alternative ways to execute the remaining program normally is
nothing but exception handling.
2. Runtime Stack Mechanism
Every java program is at least have one thread that is the Main thread.
For every thread JVM will create one runtime stack
For every method m1 present in that thread JVM will stored one entry in
the Stack this entry is called Stack Frame or Activation record.
Once the m1 method is completed the entry in the stack will be removed.
After all the methods present inside the thread completed that thread will
be terminated.
Before terminating the thread JVM will destroy the empty Stack which
created for that thread.
3. Default Exception Handling
If inside a method an exception raised the method in which it is raised is
responsible to create the exception object with the help of JVM.
In this object information will be added like below,

 Name of the exception


 Description of the exception
 Stack trace/Location(the location where problem occur)

e.g.
public class DemoPgm {
public static void main(String[] args) {
doStuff();
}
public static void doStuff(){
doMoreStuff();
}
public static void doMoreStuff(){
System.out.println(10/0);
}
}

Here in this example main method is calling the doStuff method


doStuff method is calling the doMoreStuff.
Stack
main
doStuff
doMoreStuff

In doMoreStuff arithmetic exception raised.


Once exception is occur JVM will ask doMoreStuff method for code to handle
that exception.
If no exception handled code is available it will terminate the method
abnormally, removes the corresponding entry from the stack and will go to
the parent method from where this method is called , here it is dostuff.
If doStuff also not having the implementation it will terminate the method
abnormally, removes the corresponding entry from the stack and will go to
the main method.
If main also not having the exception handling code it will terminate h
method abnormally, removes the corresponding entry from the stack, JVM
will take care of it further.
In this case as main method also not having the exception handling code,
JVM maintains a default exception handler.
JVM will hand over the object to the Default exception handler.
Default exception handler will print the information in below format
Exception in thread "main" java.lang.ArithmeticException: / by zero
at com.company.DemoPgm.doMoreStuff(DemoPgm.java:11)
at com.company.DemoPgm.doStuff(DemoPgm.java:8)
at com.company.DemoPgm.main(DemoPgm.java:5)

and terminates the program abnormally

4. Exception Hierarchy and Difference between Exception and Error


As for other java classes object class is the root class, same for all the
exceptions Throwable class is the root class
Throwable class contains two child classes
1. Exception
2. Error
Most of the time exceptions are caused by our programs only
Exceptions are recoverable
Recoverable means when exceptions are coming we can recover the the
exception by using the catch block and continue the rest of the program
execution.
Errors are not cause by our program,
Errors are non-recoverable
Examples of error Heap memory space error
Mostly the errors are cause by the lack of system resources.

For Exception some child classes are there


1. RunTimeException
This exception is having some child classes
1. ArithmeticException
2. NullPointerException
3. ClassCastException
4. IndexOutOfBoundsException
1. ArrayIndexOutOfBoundsException
2. StringIndexOutOfBoundsException
5. IllegalArgumentException
1. NumberFormatException
2. IOException
1. EndOfFileException/EOFException
2. FileNotFoundException
.
.
.
3. InterruptedException
4. RemoteException
.
.
.and multiple child classes are available

For Error some child classes are there


1. VMError
1. StackOverflowError
2. OutOfMemoryError
2. LinkageError
1. VerifyError
3. AssersionError
4. ExceptionInInitializerError
.
.
.
And many more
Difference between Checked and Unchecked Exceptions
Every Exception will be occur at the runtime only, there is no chance of
exceptions occurring at compile time.
The exceptions which are checked by compiler for smooth execution of the
program at runtime.
Whether programmer handling the exception or not these things are checked
by compiler such type of exceptions are default considered as checked
exceptions.
The exceptions which are checked by compiler whether programmer handling
or not for smooth execution of the program at runtime this exceptions are
called as checked exception.
e.g. FileNotFoundException
The Exceptions which are not checked by compiler whether the programmer
handling or not such type of exceptions are by default considered as the
unchecked exceptions
e.g. Arithmetic exception(no compile time error but at runtime exception
will come)

Error and all of its child classes are unchecked exceptions


RunTimeException and its child classes are unchecked exceptions
Except above two all other exceptions are checked exceptions.
Try-Catch Block
In Try-Catch block Try block represent the risky code.
The code which may cause a exception or error we can add it in Try block
In Catch block the handling code should be added.
If any exceptions are occurring in Try block those exceptions should be
handled in catch block.
Control-flow inside Try-Catch block
try{
Statementent s1;
Statementent s2;
Statementent s3;
}catch (Exception e)
{
Statementent s4;
}
Statementent s5;

Case-1 if there is no exception


Statement s1, s2, s3, s5 will be executed, catch block won’t execute
At the end normal termination will be there
Case-2 if exception raised at Statement s2 and corresponding catch block
matched
Statement s1 will execute
On Statement s2 once exception occur catch block will be executed after
that Statement s5 will be executed
And at the last normal termination of program will be there.
Once catch block executed control never goes back to the try block for
execution
Inside try block if an exception raised even you handled that exception
rest of the try block never going to execute. That’s why inside the try
block we only have to take risky code alone not a normal code
If multiple risky code areas are there then use multiple try-catch blocks.
Length of the try block should be as less as possible
Case-3 if the exception raised at Statement s2 and corresponding catch
block not matched (example Exception raised for ArithmaticException but
catch block is for NullPointerException)
Here Statement s1 will be executed normally but after that abnormal
termination of the program will be there.
Case-4 if the exception raised at the Statement s4 or Statement s5
If any Statement raises a exception but not a part of try block it will
always be a abnormal termination of the program
Catch block can contain another try-catch block
Methods to print exception information
Sometimes it is common requirement to print the exception information.
For printing the exception information onto the console which are the
methods available?
1. e.printStackTrace
If you want complete information about the exception we can go for this
method.
For this method System.Out.println is not required to print the message

2. e.toString() or just e
If you just want name of exception and the description we can use this
method
For this method System.Out.println is required to print the message

3. e.getMessage()
If you only want the description of the exception the we can use this
method
For this method System.Out.println is required to print the message

Default exception handler always uses e.printStackTrace method for


printing the exception.

These methods we can apply any exception object and any error object.
These methods are available in Throwable class
try with multiple catch blocks
If in our try block multiple exceptions raise chances are there, like
FileNotFoundException, ArithmeticException etc only catch block will not
be sufficient to handle the exceptions.
So in this case for multiple exceptions multiple catch block should be
provided so that for particular exception corresponding catch block will
be executing.
At the end one default (Exception e) exception catch block also should be
there in case other catch blocks are failing means it will execute.
Loophole in multiple catch block
In try with multiple catch blocks the order of catch block is very
important
The order should be from child to parent not from parent to child
try{
int i=10;
System.out.println(i/0);;
}catch (Exception e)
{
System.out.println(e);
}catch (ArithmeticException e)
{
System.out.println(e);
}

in above example first catch block is parent exception catch block


and second is the child, but here this is the problem JVM will give error
as ArithmeticException will be already caught by Exception e catch block
so the proper order should be like
try{
int i=10;
System.out.println(i/0);;
}catch (ArithmeticException e)
{
System.out.println(e);
}catch (Exception e)
{
System.out.println(e);
}

also we should not declare the similer catch block


try{
int i=10;
System.out.println(i/0);;
}catch (ArithmeticException e)
{
System.out.println(e);
} catch (ArithmeticException e)
{
System.out.println(e);
}

here in this case compiler give the error as AE exception has been already
caught

You might also like