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

Exception Java

Uploaded by

Keshav Bharadwaj
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)
8 views12 pages

Exception Java

Uploaded by

Keshav Bharadwaj
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/ 12

Exception Handling in Java

Error: Errors are the wrongs that can make a program go wrong.
Compile-time error Run-time Error
Syntax error at compile time because of Wrong logic lead to run-time error such as
• Missing Semicolons • Dividing an integer by zero

• Missing(or mismatch of) brackets in class & method Body


• Misspelling of identifiers & Keywords • Accessing an element that is out of array bound
• Missing double quotes in Strings • Trying to store a value into an array of an incompatible
• Use of undeclared variables class or type
• Incompatible types in assignments / initialization • Trying to illegally change the state of a thread
• Bad references to objects …etc. • Attempting to use a negative size for an array
Many more…
Exception (Run-time error)
❖ Exception are unusual or abnormal condition (Ex- Divide by zero)
❖ The exception handling in java is one of the powerful mechanism to handle the runtime
errors so that normal flow of the application can be maintained.
❖ Exception is an event that disrupts the normal flow of the program. It is an object which is thrown
at runtime.
What is exception handling?
❖ Exception Handling is a mechanism to handle runtime errors such as ClassNotFound, IO, SQL,
Remote etc.
Types of Exception
There are mainly two types of exceptions: checked and unchecked where error is considered as
unchecked exception.
1. Checked Exception
2. Unchecked Exception
3. Error

1) Checked Exception
• The classes that extend Throwable class except RuntimeException.
• Explicitly handled in the code itself with the help of try-catch blocks.
• These exceptions are extended from the java.lang.Exception class.
• Error are known as checked exceptions e.g. IOException, SQLException etc. Checked exceptions are
checked at compile-time.
2) Unchecked Exception
• The classes that extend RuntimeException are known as unchecked exceptions e.g.
ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc. Unchecked
exceptions are not checked at compile-time rather they are checked at runtime.
3) Error
• Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc.

Hierarchy of Java Exception classes

Common scenarios where exceptions may occur


There are given some scenarios where unchecked exceptions can occur. They are as follows:

1) Scenario where ArithmeticException occurs


If we divide any number by zero, there occurs an ArithmeticException.

int a=50/0; //ArithmeticException


2) Scenario where NullPointerException occurs
If we have null value in any variable, performing any operation by the variable occurs an NullPointerException.

String s=null; // String s=”ram”;


System.out.println(s.length()); //NullPointerException

3) Scenario where NumberFormatException occurs


The wrong formatting of any value may occur NumberFormatException. Suppose I have a string variable that
has characters, converting this variable into digit will occur NumberFormatException.

String s="abc";
int i=Integer.parseInt(s); //NumberFormatException
4) Scenario where ArrayIndexOutOfBoundsException occurs
If you are inserting any value in the wrong index, it would result ArrayIndexOutOfBoundsException as shown
below:
int a[]=new int[5];
a[10]=50; //ArrayIndexOutOfBoundsException

Exception Handling Code


The basic concepts of exception handling are throwing an exception and catching it.

try block
Statement that causes an exception Exception object creator
Throws
Exception object

catch block
Statement that handles the exception Exception Handler
Java Exception Handling Keywords
There are 5 keywords used in java exception handling.
1. try
2. catch
3. finally
4. throw
5. throws
1. Java try block (try)
✓ Java try block is used to enclose the code that might throw an exception.
✓ It must be used within the body of the method.
✓ Java try block must be followed by either catch or finally block.
2. Java catch block(catch)
✓ Java catch block is used to handle the Exception. It must be used after the try block only.
✓ We can use multiple catch block with a single try.

Syntax of java try-catch Syntax of try-finally block


1. try 9. try
2. { 10. {
3. //code that may throw exception 11. //code that may throw exception
4. } 12. }
5. catch(Exception_class_Name ref) 13. finally
6. { 14. {
7. … 15. …
8. } 16. }

Problem without exception handling


Let's try to understand the problem if we don't use try-catch block.

As displayed in the above example, rest of the code is not executed (in such case, rest of the code... statement
is not printed). There can be 100 lines of code after exception. So all the code after exception will not be
executed.

Solution by exception handling


Let's see the solution of above problem by java try-catch block.

int data=50/0; Exception Object

1) Prints out the NO YES


Exception Description
Rest of the code
Is
2) Prints the stack trace is executed
handled?
3) Terminate the program
Java Multi catch block
If you have to perform different tasks at the occurrence of different Exceptions, use java multi catch block.
Java Nested try block
The try block within a try block is known as nested try block in java.
Why use nested try block
Sometimes a situation may arise where a part of a block may cause one error and the entire block itself may
cause another error. In such cases, exception handlers have to be nested.
Syntax: Example:
1. ....
2. try
3. {
4. statement 1;
5. statement 2;
6. try
7. {
8. statement 1;
9. statement 2;
10. }
11. catch(Exception e)
12. {
13. }
14. }
15. catch(Exception e)
16. {
17. }
18. ....

3) Java finally block (finally)

✓ Java finally block is a block that is used to execute important code such as closing connection, stream etc.
✓ Java finally block is always executed whether exception is handled or not handled also.
✓ Java finally block follows try or catch block.
✓ If we don’t handle exception, before terminating the program, JVM executes finally block(if any)

Program Code

No Yes
Exception
Occurred

No Exception
Handled

Yes
Case 1
Java finally example where exception doesn't occur.

Case 2
The java finally example where exception occurs and not handled.
RULE
1. For each try block there can be zero or more catch blocks, but only one finally block.
2. The finally block will not be executed if program exits (either by calling System.exit () or by causing
a fatal error that causes the process to abort).

Case 3
The java finally example where exception occurs and handled.
Java throw keyword (throw)
The Java throw keyword is used to explicitly throw an exception. We can throw either checked or uncheked
exceptions in java by throw keyword. The throw keyword is mainly used to throw custom exception. The syntax
of java throw keyword is given below.
Type1 Type2
throw exception; throw new IOException("sorry device error);
Java throws keyword (throws)

• throw keyword is used to throw Exception from any method or static block in Java while throws keyword,
used in method declaration, denoted which Exception can possible be thrown by this method. They are not
interchangeable.
• The Java throws keyword is used to declare an exception. It gives information to the programmer that there may
occur an exception so it is better for the programmer to provide the exception handling code so that normal flow
can be maintained.
• Exception Handling is mainly used to handle the checked exceptions. If there occurs any unchecked exception
such as NullPointerException, it is programmers fault that he is not performing check up before the code being
used.

Syntax Example
returntype methodName(parameter list)throws exceptionlist void passwordCheck() throws SecurityException
{
{
throws (new securityException(“Invalid Password”));
//body of method
}
}

You might also like