Nothing Special   »   [go: up one dir, main page]

Exception Handling

Download as pdf or txt
Download as pdf or txt
You are on page 1of 62

SDE Readiness Training

Empowering Tomorrow’s Innovators


Module I
Java Software Development:
Effective Problem Solving

2 Collections in Java | © SmartCliff | Internal | Version 1.0


Exception Handling

Learning Level :

DATE : 26.09.2024
Exception handling

Realtime Scenario

• Whenever we travel in Aircraft, Airhostess used to give demonstration of steps that the passengers
have to take in case of emergency.

4 Exception handling | ©SmartCliff | Internal | Version 1.0


Exception handling

Realtime Scenario

Why these demonstration steps are important?

• The reason is that we have to be aware of how to handle a situation in case of any emergency while
you are flying.

• This scenario explains how you have to think in advance the many possibilities of mishaps that can
happen and the preventive measures to save.

5 Exception handling | ©SmartCliff | Internal | Version 1.0


Exception handling

Exception handling: Need

• Similarly, when we write the programs as a part of any application, we have to visualize the challenges
that can disrupt the normal flow of execution. If so, how to overcome these.

• In Java, Exception handling mechanism helps the programmer to have a comfortable seat when such
situation occurs.

6 Exception handling | ©SmartCliff | Internal | Version 1.0


Exception handling

What is an Exception?

• An exception is an 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.

• Below are some situations when an exception could occur

- Performing an illegal arithmetic operation.

- Inserting/accessing an array beyond its boundary.

- Accessing a file that does not exist

- etc.

7 Exception handling | ©SmartCliff | Internal | Version 1.0


Exception handling

Example

class SimpleArithmetic {
public static void main(String args[]){

int result=75/0; //exception occur


System.out.println(“Arithemetic Operation result: “+ result);
….
}
}

Output:

Exception in thread main java.lang.ArithmeticException:/ by zero

8 Exception handling | ©SmartCliff | Internal | Version 1.0


Exception handling

Exception Types

• There are three categories of exceptions

- Checked Exceptions

- Unchecked Exceptions

- Errors

9 Exception handling | ©SmartCliff | Internal | Version 1.0


Exception handling

Checked Exceptions

• It is an exception that occurs at the compile time, these are also called as compile-time exceptions.

• These exceptions cannot simply be ignored at the time of compilation, the programmer should take

care of (handle) these exceptions.


Examples:

- IOException

- ClassNotFound Exception

- SQLException

- SocketException,

- etc.,

10 Exception handling | ©SmartCliff | Internal | Version 1.0


Exception handling

Unchecked Exceptions

• An unchecked exception is an exception that occurs at the time of execution. These are also called

as Runtime Exceptions.

• These include programming bugs, such as logic errors or improper use of an API. Runtime exceptions

are ignored at the time of compilation.


Examples:

- ArithmeticException

- NullPointerException,

- ArrayIndexOutOfBoundsException

- etc.,

11 Exception handling | ©SmartCliff | Internal | Version 1.0


Exception handling

Errors

• Errors are abnormal conditions that happen in case of severe failures, these are not handled by the

Java programs.

• Errors are generated to indicate errors generated by the runtime environment.

Examples:

- OutOfMemoryError

- VirtualMachineError

- StackOverflowError

- etc.,

12 Exception handling | ©SmartCliff | Internal | Version 1.0


Exception handling

Exception handling technique

• There are several built-in classes that are used to handle the fundamental errors that may occur in your

programs.

• Also, we can create our own exceptions based on the application needs by extending Exception

class.

13 Exception handling | ©SmartCliff | Internal | Version 1.0


Exception handling

Exception Hierarchy

14 Exception handling | ©SmartCliff | Internal | Version 1.0


Exception handling

Exception Hierarchy

• All exception and errors types are subclasses of class Throwable, which is the base class of the
hierarchy. There are three main types of Throwable:

Error

• Typically, an unrecoverable external error

RuntimeException

• Typically caused by a programming mistake

Exception

• Recoverable error
Note:

• In Java exceptions under Error and RuntimeException classes are unchecked exceptions, everything else under
throwable is checked.
15 Exception handling | ©SmartCliff | Internal | Version 1.0
Exception handling

Example without handler

// Java program to demonstrate how exception is thrown.


Output:
class ThrowsExecp{
Exception in thread "main"
public static void main(String args[]){
java.lang.NullPointerException at
String str = null;
ThrowsExecp.main(File.java:8)
System.out.println(str.length());
...
}
}

In the above example, program will be terminated abruptly and the rest of codes will not get executed due to

exception

16 Exception handling | ©SmartCliff | Internal | Version 1.0


Exception handling in Java

Exception handling Mechanism

Below are the steps to handle the exceptions

Step 1: Identify the problem (Hit the Exception)

Step 2: Notify that an error has occured (Throw the Exception)

Step 3: Recieve the error notification (Catch the Exception)

Step 4: Take corrective actions (Handle the Exception)

Note:

First two steps are taken care by Try block and rest of the steps taken care by Catch block.

17 Exception handling | ©SmartCliff | Internal | Version 1.0


Exception handling

How JVM handle an Exception?

• Whenever inside a method, if an exception has occurred, the method creates an Object known as

Exception Object and hands it off to the run-time system(JVM).

• The exception object contains name and description of the exception, and current state of the

program where exception has occurred.

• Creating the Exception Object and handling it to the run-time system is called throwing an Exception.

• There could be a list of methods that were called to obtain the method in which the exception took place.

• This list of the methods is called as Call Stack.

18 Exception handling | ©SmartCliff | Internal | Version 1.0


Exception handling

Procedure for Exception Handling

• The run-time system searches the call stack to find the method that contains block of code that can

handle the occurred exception. The block of the code is called Exception handler.

• The run-time system starts searching from the method in which exception occurred, proceeds through

call stack in the reverse order in which methods were called.

• If it finds appropriate handler (the type of the exception object thrown matches the type of the

exception object it can handle) then it passes the occurred exception to it.

• If couldn’t have found the appropriate handler then run-time system handover the Exception Object
to default exception handler , which is part of run-time system. This handler prints the exception
information and terminates program abnormally.
19 Exception handling | ©SmartCliff | Internal | Version 1.0
Exception handling

Exception handling: Keywords

Keyword Description

to specify a block where we should place exception


try code. The try block must be followed by either catch
or finally. It means, we can't use try block alone.
to handle the exception. It must be preceded by try
catch block which means we can't use catch block alone. It
can be followed by finally block later.
The to execute the important code of the program. It
finally
is executed whether an exception is handled or not.
throw to throw an exception.
to declare exceptions. It doesn't throw an exception.
throws It specifies that there may occur an exception in the
method. It is always used with method signature.

20 Exception handling | ©SmartCliff | Internal | Version 1.0


Exception handling

Try-catch block

try{
….
-- code which may cause an exception
….
}

catch(ExceptionType e){

-- Code to handle the exception

}

21 Exception handling | ©SmartCliff | Internal | Version 1.0


Exception handling

Example with handler: Example #1

// Java program to demonstrate exception handling.


class ThrowsExecp{
public static void main(String args[]){
try{
String str = null;
System.out.println(str.length());
}
catch(NullPointerException e){
System.out.println(e);
}
System.out.println(“rest of the code”);//rest of the code
}
}

22 Exception handling | ©SmartCliff | Internal | Version 1.0


Exception handling

Example with handler : Example #2

// Java program to demonstrate exception handling.

public class ExcepDemo{


public static void main(String args[]) {
try {
int a[] = new int[2];
System.out.println("Access element three :" + a[3]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Exception thrown :" + e);
}
System.out.println("Out of the block");
}
}

23 Exception handling | ©SmartCliff | Internal | Version 1.0


Exception handling

Printing Exception Messages

• 3 different ways to print Exception messages in Java

• java.lang.Throwable.printStackTrace() method :we can print the name(e.g.


java.lang.ArithmeticException), description(e.g. / by zero) of an exception separated by colon and stack
trace (where that exception has occurred) in the next line.

e.printStackTrace();

• toString() method :we can print only name and description of an exception

System.out.println(e.toString()); (or) System.out.println(e);

• java.lang.Throwable.getMessage() method : we can print only description of an exception.

System.out.println(e.getMessage());

24 Exception handling | ©SmartCliff | Internal | Version 1.0


Exception handling

Multiple catch statements

• A single block of code can raise more than one exception

• You can specify two or more catch clauses, each can catch different type of exception

• When an exception is thrown, each catch statement is inspected in order, and the first one whose

type matches that of the exception is executed

• After one catch statement executes, the others are bypassed, and execution continues after the

try/catch block

• It is mandatory to handle the exceptions according to their inheritance hierarchy.

25 Exception handling | ©SmartCliff | Internal | Version 1.0


Exception handling

Multiple catch statements

try {

// block of code to monitor for errors

// the code you think can raise an exception

catch (ExceptionType1 exOb) {

// exception handler for ExceptionType1

26 Exception handling | ©SmartCliff | Internal | Version 1.0


Exception handling

Multiple catch statements

catch (ExceptionType2 exOb) {

// exception handler for ExceptionType2

catch (ExceptionType3 exOb) {

// exception handler for ExceptionType3

27 Exception handling | ©SmartCliff | Internal | Version 1.0


Exception handling

Multiple catch block: Example #1

// Java program to demonstrate multiple catch block.


public class ExceptionDemo{
public static void main(String args[]){
try{
int a[]=new int[5];
a[5]=30/0;
}
catch(ArithmeticException e){
System.out.println(e);
}

28 Exception handling | ©SmartCliff | Internal | Version 1.0


Exception handling

Multiple catch block: Example #1

catch(ArrayIndexOutOfBoundsException e) {
System.out.println(e);
}
catch(Exception e) {
System.out.println(e);
}
System.out.println("rest of the code...");
}
}

29 Exception handling | ©SmartCliff | Internal | Version 1.0


Exception handling

Multiple catch block: Example #2

// Java program to demonstrate multiple catch block.


public class ExceptionDemo{
public static void main(String args[]){
try{
int a[]=new int[5];
a[5]=30/0;
}
catch(Exception e) {
System.out.println(e);
}

30 Exception handling | ©SmartCliff | Internal | Version 1.0


Exception handling

Multiple catch block: Example #2

catch(ArithmeticException e){ Output: Error


System.out.println(e);
} Note:
catch(ArrayIndexOutOfBoundsException e) {
•At a time only one Exception is
System.out.println(e);
occurred and at a time only one catch
}
System.out.println("rest of the code...");
block is executed.

} • All catch blocks must be ordered from


} most specific to most general i.e. catch
for ArithmeticException must come
before catch for Exception .

31 Exception handling | ©SmartCliff | Internal | Version 1.0


Exception handling

throw keyword

• The throw keyword in Java is used to explicitly throw an exception from a method or any block of code.

• We can throw either checked or unchecked exception by throw keyword.

• The throw keyword is mainly used to throw user defined exception.

Syntax:

throw exception;

32 Exception handling | ©SmartCliff | Internal | Version 1.0


Exception handling

throw keyword: Example #1

// Java program to demonstrate the use of throw keyword.


public class ExceptionDemo{
static void validate(int num){
if(num<0)
throw new ArithmeticException(“Invalid value");
else
System.out.println(“Valid to proceed");
}

33 Exception handling | ©SmartCliff | Internal | Version 1.0


Exception handling

throw keyword: Example #1

public static void main(String args[]){


try{
validate(-10);
}
catch(Exception e){
System.out.println(“Error:"+e);
}
System.out.println("rest of the code...");
}
}

34 Exception handling | ©SmartCliff | Internal | Version 1.0


Exception handling

throw keyword: Example #2

// Java program to demonstrate the use of throw keyword.


class ExceptionDemo{
static void fun() {
try{
throw new NullPointerException(“Demo");
}
catch(NullPointerException e) {
System.out.println("Caught inside fun().");
throw e; // rethrowing the exception
}
}

35 Exception handling | ©SmartCliff | Internal | Version 1.0


Exception handling

throw keyword: Example #2

public static void main(String args[]) {


try {
fun();
}
catch(NullPointerException e) {
System.out.println("Caught in main.");
}
}
}

36 Exception handling | ©SmartCliff | Internal | Version 1.0


Exception handling

throws keyword

• throws is a keyword in Java which is used in the signature of method to indicate that this method might

throw one of the listed type exceptions.

• The caller to these methods has to handle the exception using a try-catch block.

• It provides information to the caller of the method about the exception.

• To handle the exception when you call this method, all the exceptions that are declared using throws,

must be handled where you are calling this method else you will get a compilation error.

Syntax:
type method_name(parameters) throws exception_list

37 Exception handling | ©SmartCliff | Internal | Version 1.0


Exception handling

throws keyword: Example #1


// Java program to demonstrate the use of throws keyword.
class ExceptionDemo{
static void fun() throws IllegalAccessException {
System.out.println("Inside fun(). ");
throw new IllegalAccessException("demo");
}
public static void main(String args[]) {
try{
fun();
}
catch(IllegalAccessException e) {
System.out.println("caught in main.");
}
} }
38 Exception handling | ©SmartCliff | Internal | Version 1.0
Exception handling

throws keyword: Example #2

// Java program to demonstrate the use of throws keyword.


import java.io.*;
class ThrowExample {
void myMethod(int num)throws IOException, ClassNotFoundException{
if(num==1)
throw new IOException("IOException Occurred");
else
throw new ClassNotFoundException("ClassNotFoundException");
}
}

39 Exception handling | ©SmartCliff | Internal | Version 1.0


Exception handling

throws keyword: Example #2

public class ExceptionDemo{


public static void main(String args[]){
try{
ThrowExample obj=new ThrowExample();
obj.myMethod(1);
}
catch(Exception ex){
System.out.println(ex);
}
}
}

40 Exception handling | ©SmartCliff | Internal | Version 1.0


Exception handling

finally block

• finally block is a block that is used to execute important code such as closing connection, stream etc.

• It is guaranteed to be executed whether the exception is handled or not.

• It follows try or catch block.

Note: If you don't handle exception, before terminating the program, JVM executes finally block(if any).

41 Exception handling | ©SmartCliff | Internal | Version 1.0


Exception handling

finally block: Example #1

// Java program to demonstrate finally block.


class ExceptionDemo{
public static void main(String args[]) {
try {
int data=25/5;
System.out.println(data);
}
catch(NullPointerException e) {
System.out.println(e);
}
finally {
System.out.println("finally block is always executed");
}
System.out.println("rest of the code..."); } }
42 Exception handling | ©SmartCliff | Internal | Version 1.0
Exception handling

finally, keyword: Example #2


// Java program to demonstrate finally block.
class ExceptionDemo{
public static void main(String args[]) {
try {
int data=25/0;
System.out.println(data);
}
catch(NullPointerException e) {
System.out.println(e);
}
finally {
System.out.println("finally block is always executed");
}
System.out.println("rest of the code..."); } }
43 Exception handling | ©SmartCliff | Internal | Version 1.0
Exception handling

finally, keyword: Example #3


// Java program to demonstrate finally block.
class ExceptionDemo{
public static void main(String args[]) {
try {
int data=25/0;
System.out.println(data);
}
catch(ArithmeticException e) {
System.out.println(e);
}
finally {
System.out.println("finally block is always executed");
}
System.out.println("rest of the code..."); } }
44 Exception handling | ©SmartCliff | Internal | Version 1.0
Exception handling

User defined Exceptions

• Java provides extensive set of in-built exceptions

• But there may be cases where we may have to define our own exceptions which are application specific

• We can customize the exception according to our need and purpose.

• While creating user defined exceptions, the following aspects have to be taken care :

- The user defined exception class should extend from the Exception class and its Subclass.

- If we want to display meaningful information about the exception, we should override the toString()

method

45 Exception handling | ©SmartCliff | Internal | Version 1.0


Exception handling

User defined Exceptions: Example #1

// Java program to demonstrate user defined exception.


class InvalidAgeException extends Exception {
InvalidAgeException(String s) {
// Call constructor of parent Exception
super(s);
}
}
class ExceptionDemo{
static void validate(int age)throws InvalidAgeException {
if(age<18)
throw new InvalidAgeException("not eligible");
else
System.out.println(“Eligible");
}
46 Exception handling | ©SmartCliff | Internal | Version 1.0
Exception handling

User defined Exceptions: Example #1

public static void main(String args[]) {


try {
validate(13);
}
catch(Exception m) {
System.out.println("Exception occured: "+m);
}

System.out.println("rest of the code...");


}
}

47 Exception handling | ©SmartCliff | Internal | Version 1.0


Exception handling

User defined Exceptions: Example #2

// Java program to demonstrate user defined exception.


class InvalidProductException extends Exception{
public InvalidProductException(String s) {
// Call constructor of parent Exception
super(s);
}
}

public class ExceptionDemo {


void productCheck(int weight) throws InvalidProductException{
if(weight<100){
throw new InvalidProductException("Product Invalid");
}
}
48 Exception handling | ©SmartCliff | Internal | Version 1.0
Exception handling

User defined Exceptions: Example #2

public static void main(String args[]) {


ExceptionDemo obj = new ExceptionDemo();
try {
obj.productCheck(60);
}
catch (InvalidProductException ex) {
System.out.println("Caught the exception");
System.out.println(ex.getMessage());
}
}
}

49 Exception handling | ©SmartCliff | Internal | Version 1.0


Exception handling

Assertions

• It is used for testing the correctness of any assumptions that have been made in the program.

• An assert statement is used to declare an expected boolean condition in a program.

• When the program is running with assertions enabled, the condition is checked at runtime. If the
condition is false, the Java runtime system throws an AssertionError.

• It is mainly used for testing purposes during development.

Syntax:

assert expression; (or)

assert expression1 : expression2;

50 Exception handling | ©SmartCliff | Internal | Version 1.0


Exception handling

Assertions

• By default, assertions are disabled. We need to run the code as given.

Enabling Assertions

• java –ea Test (or) java –enableassertions Test

Here, Test is the file name.

Disabling Assertions

• java –da Test (or) java –disableassertions Test

Here, Test is the file name.

51 Exception handling | ©SmartCliff | Internal | Version 1.0


Exception handling

Assertions: Example #1

// Java program to demonstrate syntax of assertion


class AssertionDemo{
public static void main( String args[] ) {
int value = 55;
assert value >= 60:"Wrong Data";
System.out.println("value is "+value);
}
}

52 Exception handling | ©SmartCliff | Internal | Version 1.0


Exception handling

Assertions: Example #2

// Java program to demonstrate syntax of assertion


import java.util.Scanner;
class AssertionDemo{
public static void main( String args[] ){
Scanner scanner = new Scanner( System.in );
System.out.print("Enter ur age ");
int value = scanner.nextInt();
assert value>=18:" You are not Eligble for Vote";
System.out.println("Your age: "+value);
}
}

53 Exception handling | ©SmartCliff | Internal | Version 1.0


Exception handling

Assertions: Example #3
// Java program to demonstrate syntax of assertion
import java.util.Scanner;
class AssertionDemo{
public void Test(int a){
assert a>=18:" You are not Eligble for Vote";
System.out.println("Your age: "+a);
}
public static void main( String args[] ) {
AssertionDemo obj=new AssertionDemo();
Scanner scanner = new Scanner( System.in );
System.out.print("Enter your age ");
int value = scanner.nextInt();
obj.Test(value);
}
}
54 Exception handling | ©SmartCliff | Internal | Version 1.0
Exception handling

Assertions

Where to use Assertions

• Arguments to private methods.

• Use assertion in the default case of the Switch statement

• Conditional cases.

• Conditions at the beginning of any method.

Where not to use Assertions


• Should not be used to replace error messages.
• Do not use assertions for argument checking in public methods
• Avoid catching the assertion-related exceptions.
• Should not be used on command line arguments.
• Avoid the use of evaluating more than one condition in an assertion

55 Exception handling | ©SmartCliff | Internal | Version 1.0


Exception handling

Quiz

1.Exception is a class/interface/abstract class/other?

a) Class b) Interface

c) Abstract Class d) None of the above

a) Class

56 Exception handling | ©SmartCliff | Internal | Version 1.0


Exception handling

Quiz

2. Exception is found in which package in java

a) java.lang b) java.util

c) java.io d) java.awt.

e) None of the above

a) java.lang

57 Exception handling | ©SmartCliff | Internal | Version 1.0


Exception handling

Quiz

3. Which is valid about java.lang.Exceptions?

a) The class Exception and


all its subclasses that are b) The class Error and all its
not also subclasses of subclasses are unchecked
RuntimeException are exceptions
checked exceptions

c)The class RuntimeException d) All the above


and all its subclasses are
unchecked exceptions

d) All the above

58 Exception handling | ©SmartCliff | Internal | Version 1.0


Exception handling

Quiz

4. Which of these is valid code snippet in exception handling


in java?

a) catch{ } b) finally{ }

c) try{ }
d) try{ }.
catch(Exception e){ }
finally{ }

c) try{ }
catch(Exception e){ }
finally{ }

59 Exception handling | ©SmartCliff | Internal | Version 1.0


Exception Handling

Quiz

5. Which is invalid statement in Exception handling in java?

a) finally block can't b) try block can throw


throw exception exception

c) catch block can throw d) finally block can throw


exception exception.

e) None of the above

a) finally block can't throw


exception

60 Exception handling | ©SmartCliff | Internal | Version 1.0


An investment in
knowledge pays the
best interest.
- Benjamin Franklin

61 Collections in Java | © SmartCliff | Internal | Version 1.0


THANK YOU

You might also like