0% found this document useful (0 votes)
14 views

Week 11 Exception

ddddddddddddddddddd

Uploaded by

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

Week 11 Exception

ddddddddddddddddddd

Uploaded by

nirew71345
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

Khulna Khan Bahadur Ahsanullah University

Department of CSE
Course Title: Object Oriented Programming
Course Code: CSE 061 1203
Week - 11
Class – 01

1. What is Exception Handling?

• Exception Handling in Java is one of the effective means to handle runtime


errors so that the regular flow of the application can be preserved.
• Java Exception Handling is a mechanism to handle runtime errors such as
ClassNotFoundException, IOException, SQLException, RemoteException.

2. What are Java Exceptions?


• 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.

1|Page
3. Major reasons why an exception Occurs
• Invalid user input
• Device failure
• Loss of network connection
• Physical limitations (out-of-disk memory)
• Code errors
• Opening an unavailable file

4. What is the difference between Error and Exception?


Error: An Error indicates a serious problem that a reasonable application
should not try to catch.
Exception: Exception indicates conditions that a reasonable application might
try to catch.

5. Exception Hierarchy
• All exception and error types are subclasses of the class Throwable, which
is the base class of the hierarchy.
• One branch is headed by Exception.
• This class is used for exceptional conditions that user programs should catch.
• NullPointerException is an example of such an exception.
• Another branch, Error is used by the Java run-time system(JVM) to
indicate errors having to do with the run-time environment itself(JRE).
StackOverflowError is an example of such an error.

2|Page
Java Exception Hierarchy

6. Types of Exceptions
Java defines several types of exceptions that relate to its various class libraries.
Java also allows users to define their own exceptions.

3|Page
Exceptions can be categorized in two ways:
1. Built-in Exceptions
➢ Checked Exception
➢ Unchecked Exception
2. User-Defined Exceptions
Let us discuss the above-defined listed exception that is as follows:

What is Built-in Exception?


Built-in exceptions are the exceptions that are available in Java libraries. These
exceptions are suitable to explain certain error situations.
➢ Checked Exceptions: Checked exceptions are called compile-time exceptions
because these exceptions are checked at compile-time by the compiler.
➢ Unchecked Exceptions: The unchecked exceptions are just opposite to the
checked exceptions. The compiler will not check these exceptions at compile
time. In simple words, if a program throws an unchecked exception, and even
if we didn’t handle or declare it, the program would not give a compilation error.

What is User-Defined Exceptions?


Sometimes, the built-in exceptions in Java are not able to describe a certain
situation. In such cases, users can also create exceptions, which are called ‘user-
defined Exceptions’.
The advantages of Exception Handling in Java are as follows:
1. Provision to Complete Program Execution
2. Easy Identification of Program Code and Error-Handling Code
3. Propagation of Errors
4. Meaningful Error Reporting
5. Identifying Error Types
4|Page
Class – 02

Methods to print the Exception information:


1. printStackTrace()
This method prints exception information in the format of the Name of the
exception: description of the exception, stack trace.
Example:

//program to print the exception information using printStackTrace() method


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();
}
}
}

Output:
java.lang.Arithmetic Exception:/by zero
at GFG.main(File.java:10)

5|Page
2. toString()
The toString() method prints exception information in the format of the Name of
the exception: description of the exception.

//program to print the exception information using toString() method

import java.io.*;

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

Output: java.lang.ArithmeticException: / by zero

6|Page
3. getMessage()
The getMessage() method prints only the description of the exception.

//program to print the exception information using getMessage() method

import java.io.*;

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

Output: / by zero

7|Page
Class – 03

How Programmer Handle an Exception?


Customized Exception Handling: Java exception handling is managed via five
keywords: try, catch, throw, throws, and finally. Briefly, here is how they work.
Program statements that you think can raise exceptions are contained within a try
block. If an exception occurs within the try block, it is thrown. Your code can catch
this exception (using catch block) and handle it in some rational manner. System-
generated exceptions are automatically thrown by the Java run-time system. To
manually throw an exception, use the keyword throw. Any exception that is thrown
out of a method must be specified as such by a throws clause. Any code that
absolutely must be executed after a try block completes is put in a finally block.

Need for try-catch clause (Customized Exception Handling)


Consider the below program in order to get a better understanding of the try-catch
clause.

// Need of try-catch Clause


class GFG {

// Main driver method


public static void main(String[] args)
{
// Taking an array of size 4
int[] arr = new int[4];

8|Page
// Now this statement will cause an exception
int i = arr[4];

// This statement will never execute


// as above we caught with an exception
System.out.println("Hi, I want to execute");
}
}

Output

Output explanation: In the above example, an array is defined with size i.e. you
can access elements only from index 0 to 3. But you trying to access the elements
at index 4(by mistake) that’s why it is throwing an exception. In this case, JVM
terminates the program abnormally. The statement System.out.println(“Hi, I want
to execute”); will never execute. To execute it, we must handle the exception using
try-catch. Hence to continue the normal flow of the program, we need a try-catch
clause.

How to Use the Try-catch Clause?


try {
// block of code to monitor for errors
// the code you think can raise an exception
} catch (ExceptionType1 exOb) {

9|Page
// exception handler for ExceptionType1
} catch (ExceptionType2 exOb) {
// exception handler for ExceptionType2
}
// optional
finally { // block of code to be executed after try block ends
}

Certain key points need to be remembered that are as follows:


• In a method, there can be more than one statement that might throw an
exception, So put all these statements within their own try block and provide a
separate exception handler within their own catch block for each of them.
• If an exception occurs within the try block, that exception is handled by the
exception handler associated with it. To associate the exception handler, we
must put a catch block after it. There can be more than one exception handler.
Each catch block is an exception handler that handles the exception to the type
indicated by its argument. The argument, ExceptionType declares the type of
exception that it can handle and must be the name of the class that inherits from
the Throwable class.
• For each try block, there can be zero or more catch blocks, but only one final
block.
• The finally block is optional. It always gets executed whether an exception
occurred in try block or not. If an exception occurs, then it will be executed
after try and catch blocks. And if an exception does not occur, then it will be
executed after the try block. The finally block in Java is used to put important
codes such as clean-up code e.g., closing the file or closing the connection.
• If we write System.exit in the try block, then finally block will not be executed.
10 | P a g e
The summary is depicted via visual aid below as follows:

11 | P a g e

You might also like