Exceptions-exception hierarchy-throwing and catching

PackialathaVISTAS 18 views 34 slides Aug 31, 2025
Slide 1
Slide 1 of 34
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19
Slide 20
20
Slide 21
21
Slide 22
22
Slide 23
23
Slide 24
24
Slide 25
25
Slide 26
26
Slide 27
27
Slide 28
28
Slide 29
29
Slide 30
30
Slide 31
31
Slide 32
32
Slide 33
33
Slide 34
34

About This Presentation

Exceptions-exception hierarchy-throwing and catching
exceptions-built-in exceptions, creating own
exceptions, Stack Trace Elements. Input /Output
Basics-Streams-Byte streams


Slide Content

UNIT - III Exception Handling and I/O

Exceptions-exception hierarchy-throwing and catching exceptions-built-in exceptions , creating own exceptions, Stack Trace Elements. Input /Output Basics-Streams-Byte streams and character streams-Reading and Writing Console-Reading and Writing Files Templates

Difference between error and exception Errors indicate serious problems and abnormal conditions that most applications should not try to handle. Error defines problems that are not expected to be caught under normal circumstances by our program . For example memory error, hardware error, JVM error etc.

Exceptions Exceptions are conditions within the code. A developer can handle such conditionsand take necessary corrective actions. Few examples  DivideByZero exception  NullPointerException  ArithmeticException  ArrayIndexOutOfBoundsException o An exception (or exceptional event) is a problem that arises during the execution of a program. o When an Exception occurs the normal flow of the program is disrupted and the program/Application terminates abnormally, which is not recommended, therefore, these exceptions are to be handled.

Exception Hierarchy

Checked Exceptions These are the exceptions which occur during the compile time of the program. The compiler checks at the compile time that whether the program contains handlers for checked exceptions or not. NoSuchFieldException InstantiationException IllegalAccessException ClassNotFoundException NoSuchMethodException CloneNotSupportedException InterruptedException

Unchecked Exceptions Unchecked exceptions are the exceptions which occur during the runtime of the program. These exceptions cannot be anticipated and recovered like programming bugs, such as logic errors or improper use of an API. These type of exceptions are also called Runtime exceptions that are usually caused by data errors, like arithmetic overflow, divide by zero etc.

Here is the list of unchecked exceptions. IndexOutOfBoundsException ArrayIndexOutOfBoundsException ClassCastException ArithmeticException NullPointerException IllegalStateException SecurityException

Error The errors in java are external to the application. An Error indicates serious problems that a reasonable application should not try to catch. Most such errors are abnormal conditions.

Exception Indication of problem during execution Uses of exception handling Process exceptions from program components Handle exceptions in a uniform manner in large projects Remove error-handling code from “main line” of execution A method detects an error and throws an exception Exception handler processes the error Uncaught exceptions yield adverse effects Might terminate program execution

13 Exception Handler Exception "thrown" here Exception handler Exception handler Thrown exception matched against first set of exception handlers If it fails to match, it is matched against next set of handlers, etc. If exception matches none of handlers, program is abandoned

Java exception handling is managed by via five keywords: try, catch, throw, throws, and finally Program statements to monitor are contained within a try block If an exception occurs within the try block, it is thrown Code within catch block catch the exception and handle it 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 before a method returns is put in a finally block General form of an e xception-handling block try{ // block of code to monitor for errors } catch ( ExceptionType1 exOb ){ // exception handler for ExceptionType1 } catch ( ExceptionType2 exOb ){ // exception handler for ExceptionType2 } //… finally{ // block of code to be executed before try block ends }

Using try and catch Handling an exception has two benefits, It allows you to fix the error It prevents the program from automatically terminating The catch clause should follow immediately the try block Once an exception is thrown, program control transfer out of the try block into the catch block Once the catch statement has executed, program control continues with the next line in the program following the entire try/catch mechanism

17 Output: Division by zero. After catch statement.

A try and catch statement form a unit. The scope of the catch clause is restricted to those statements specified by the immediately preceding try statement You cannot use try on a single statement Multiple catch Clauses: If more than one error can occur, then we use multiple catch clauses 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

If no command line argument is provided, then you will see the following output: a = 0 Divide by 0: java.lang.ArithmeticException : / by zero After try/catch blocks If any command line argument is provided, then you will see the following output: a = 1 Array index oob : java.lang.ArrayIndexOutOfBoundsException After try/catch blocks.

Nested try Statements A try statement can be inside the block of another try Each time a try statement is entered, the context of that exception is pushed on the stack If an inner try statement does not have a catch, then the next try statement’s catch handlers are inspected for a match If a method call within a try block has try block within it, then then it is still nested try

When no parameter is given: Divide by 0: java.lang.ArithmeticException: / by zero When one parameter is given a = 1 Divide by 0: java.lang.ArithmeticException: / by zero When two parameters are given a = 2 Array index out-of-bounds: java.lang.ArrayIndexOutOfBoundsException

throw It is possible for your program to throw an exception explicitly throw TrrowableInstance Here, TrrowableInstance must be an object of type Throwable or a subclass Throwable There are two ways to obtain a Throwable objects: Using a parameter into a catch clause Creating one with the new operator

Output: Caught inside demoproc . Recaught : java.lang.NullPointerException : demo Output: Caught inside demoproc . Recaught : java.lang.NullPointerException : demo

throws If a method is capable of causing an exception that it does not handle, it must specify this behavior so that callers of the method can guard themselves against that exception type method-name parameter-list) throws exception-list { // body of method } It is not applicable for Error or RuntimeException, or any of their subclasses

Output: Inside throwOne. Caught java.lang.IllegalAccessException: demo

finally It is used to handle premature execution of a method (i.e. a method open a file upon entry and closes it upon exit) finally creates a block of code that will be executed after try/catch block has completed and before the code following the try/catch block finally clause will execute whether or not an exception is thrown

User-Defined Exceptions Sometimes, the built-in exceptions in Java are not able to describe a certain situation. In such cases, user can also create exceptions which are called ‘user-defined Exceptions’.

class MyOwnException extends Exception { public MyOwnException (String msg ) { super( msg ); } } class EmployeeTest { static void employeeAge ( int age) throws MyOwnException { if(age < 0) throw new MyOwnException ("Age can't be less than zero"); else System.out.println ("Input is valid!!"); } public static void main(String[] args ) { try { employeeAge (-2); } catch ( MyOwnException e) { e.printStackTrace (); } } }

THANK YOU.
Tags