EXCEPTION HANDLING OR ERROR HANDLING.

Slides:



Advertisements
Similar presentations
Chapter 17 Failures and exceptions. This chapter discusses n Failure. n The meaning of system failure. n Causes of failure. n Handling failure. n Exception.
Advertisements

1 Exceptions: An OO Way for Handling Errors Rajkumar Buyya Grid Computing and Distributed Systems (GRIDS) Laboratory Dept. of Computer Science and Software.
Topics Introduction Types of Errors Exceptions Exception Handling
Java Programming 3 Dr. Priti Srinivas Sajja Introductory concepts of java programming as specified in MCA 302:Object Oriented Programming Using Java,
Lecture 23 Input and output with files –(Sections 2.13, 8.7, 8.8) Exceptions and exception handling –(Chapter 17)
Index Exception handling Exception In Java Exception Types
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 13 Exception Handling.
Exception Handling1. 2 Exceptions  Definition  Exception types  Exception Hierarchy  Catching exceptions  Throwing exceptions  Defining exceptions.
Exception Handling Chapter 12.  Errors- the various bugs, blunders, typos and other problems that stop a program from running successfully  Natural.
Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.
Exception Handling. Introduction An exception is an abnormal condition that arises in a code sequence at run time. In computer languages that do not support.
1 Lecture 11 Interfaces and Exception Handling from Chapters 9 and 10.
1 Lecture 4 Exception Handling. 2 Exception-Handling Fundamentals An exception is an abnormal condition that arises in a code sequence at run time A Java.
1 Nested Classes O. 2 Possible to declare a class within another class; called nested classes Nested class should have some specific association with.
Exceptions Three categories of errors: Syntax errors Runtime errors Logic errors Syntax errors: rules of the language have not been followed. Runtime error:
Exceptions in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Introduction to Java Chapter 11 Error Handling. Motivations When a program runs into a runtime error, the program terminates abnormally. How can you handle.
Exceptions. Many problems in code are handled when the code is compiled, but not all Some are impossible to catch before the program is run  Must run.
Chapter 13 Exception Handling F Claiming Exceptions F Throwing Exceptions F Catching Exceptions F Rethrowing Exceptions  The finally Clause F Cautions.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 18 Exception Handling.
Exception Handling 1. Introduction Users may use our programs in an unexpected ways. Due to design errors or coding errors, our programs may fail in unexpected.
Object Oriented Programming
EXCEPTION HANDLING.
Exception Handling in Java Exception Handling Introduction: After completing this chapter, you will be able to comprehend the nature and kinds.
Java Programming Exception Handling. The exception handling is one of the powerful mechanism provided in java. It provides the mechanism to handle the.
Object Oriented Programming with Java (150704).  Throwable Exception (This class will catch exceptions generated by prog.) (Create your own custom exception.
Exception Handling Unit-6. Introduction An exception is a problem that arises during the execution of a program. An exception can occur for many different.
Exceptions in Java. Exceptions An exception is an object describing an unusual or erroneous situation Exceptions are thrown by a program, and may be caught.
Exception Handling in Java Topics: Introduction Errors and Error handling Exceptions Types of Exceptions Coding Exceptions Summary.
Exceptions in Java. What is an exception? An exception is an error condition that changes the normal flow of control in a program Exceptions in Java separates.
Exception-Handling Fundamentals  A Java exception is an object that describes an exceptional (that is, error) condition that has occurred in a piece of.
Exceptions Handling Prepared by: Ligemm Mae del Castillo.
1 Exceptions. 2 Syntax Errors, Runtime Errors, and Logic Errors syntax errors, runtime errors, and logic errors You learned that there are three categories.
Lecture10 Exception Handling Jaeki Song. Introduction Categories of errors –Compilation error The rules of language have not been followed –Runtime error.
Throw, Throws & Try-Catch Statements Explanations and Pictures from: Reference:
Garbage Collection It Is A Way To Destroy The Unused Objects. To do so, we were using free() function in C language and delete() in C++. But, in java it.
Agenda Introduction Errors and Exception Exception Hierarchy Classification of Exceptions Built in Exceptions Exception Handling in Java User defined.
Exception Handling. You learned that there are three categories of errors: syntax errors, runtime errors, and logic errors. Syntax errors arise because.
Chapter 14 – Exception Handling
Exceptions: When things go wrong
Chapter 10 – Exception Handling
MIT AITI 2003 Lecture14 Exceptions
Java Programming Language
Chapter 13 Exception Handling
Topic: Exception Handling
Introduction to Exceptions in Java
Introduction Exception handling Exception Handles errors
Introduction to Exceptions in Java
Introduction to OO Program Design
COMPSCI 230 S Programming Techniques
Multithreading in Java
Exceptions "A slipping gear could let your M203 grenade launcher fire when you least expect it. That would make you quite unpopular in what's left of your.
Advanced Programming Behnam Hatami Fall 2017.
E x c e p t i o n s Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live. — Martin Golding.
ATS Application Programming: Java Programming
Chapter 12 Exception Handling
OBJECT ORIENTED PROGRAMMING
Web Design & Development Lecture 7
Exception Handling in Java
Managing Errors and Exceptions
Lecture 11 Objectives Learn what an exception is.
Errors and Exceptions Error Errors are the wrongs that can make a program to go wrong. An error may produce an incorrect output or may terminate the execution.
Java Programming Exceptions CSC 444 By Ralph B. Bisland, Jr.
Tutorial Exceptions Handling.
Chapter 12 Exception Handling and Text IO Part 1
Tutorial MutliThreading.
Java Basics Exception Handling.
Exception Objects An exception is an abnormal condition that arises in a code sequence at rum time. Exception is a way of signaling serious problem.
Exception Handling.
Java Programming: From Problem Analysis to Program Design, 4e
Presentation transcript:

EXCEPTION HANDLING OR ERROR HANDLING

- Error means mistakes or buggs - Error is classified into types What is Error? - Error means mistakes or buggs - Error is classified into types Error Compile Time Error Run Time Error All syntax errors will be detected And displayed by the Java compi ler and therefore these errors Are known as compile – time – errors A program may compile success fully creating the .exe file but not run properly. Such programs may produce wrong results due to wrong loaic or may terminate due to errors Missing Semicolon Missing brackets in classes and methods 3. Use of undeclared variables Dividing an integer by zero Accessing an element that is out of the bounds of an array

Some Example of Runtime Errors class Error_Handling { public static void main(String args[]) int a,b,c; a = 10; b = 0; c = a / b; System.out.println("The Value of the C Value is:" + c); } Output: / by zero

Exception Types Throwable Exception (or) RuntimeException Error 1. All Exception types are subclasses of the built – in class Throwable. Throwable is at the top of the exception class hierarchy Throwable Exception (or) RuntimeException Error This class is used for exceptional conditions that user programs should catch. This is also the class That you will subclass to create your own custom exception types Which defines exceptions that are not Expected to be caught under normal Circumstances by our program. Ex. Stack overflow

Uncaught Exception class Error_Handling { public static void main(String args[]) int i,j,k1,k2; i = 10; j = 0; k1 = i / j; k2 = i + j; System.out.println("The Division of the K1 Value is: " + k1); System.out.println("The addition of the K2 Value is: " + k2); } Output: java.lang.ArithmeticException: / by zero at Error_Handling.main(Error_Handling.java:4) In this example, we haven’t supplied any exception handlers of our own, so the exception is caught by the default handler provided by the java run – time system

What is Exceptions? An Exception is condition that is caused by a run – time error in the program. What is Exception Handling? If the exception object is not caught and handled properly, the compiler will display an error message and will terminate the program. If we want the program to continue with the execution of the remaining appropriate message for taking corrective actions. This task is known as exception handling. Exceptions Types Exception Asynchronous Exception Synchronous Exception Keyboard Interrupt Mouse Interrupt Division by Zero

Catches and handles the Exception Handling Mechanism The purpose of the exception handling mechanism is to provide means to detect and report an “exceptional circumstance”, so that appropriate action can be taken. The Error Handling code that performs the following tasks: 1. Find the problem (Hit the Exception) 2. Inform that an error has occurred (Throw the exception) 3. Receive the error information (Catch the exception) 4. Take corrective actions (Handle the exception) try block Detects and throws an exception catch block Catches and handles the exception Exception object

Using try and catch //Block of statements which detects and ------------------ try { ------------- } catch(Exception_Type e) -------------- //Block of statements which detects and //throws an exception //Catches exception //Block of statements that handles the //exception

Example Program for Exception Handling Mechanism class Error_Handling { public static void main(String args[]) int i,j,k1,k2; i = 10; j = 0; try k1 = i / j; System.out.println("The Division of the K1 Value is: " + k1); } catch(ArithmeticException e) System.out.println("Division by Zero"); k2 = i + j; System.out.println("The addition of the K2 Value is: " + k2); There is an Exception Catches the exception Output: Division by Zero, The addition of the K2 Value is:10

Multiple Catch Statements It is possible that a program segment has more than one condition to throw an exception. try { //statements } catch(Exception-Type-1 e) catch(Exception-Type-2 e) ----------- catch(Exception-Type-N e)

class Error_Handling { public static void main(String args[]) int a[ ] = {5,10}; int b = 5; try int x = a[2] / b - a[1]; } catch(ArithmeticException e) System.out.println("Division by Zero"); catch(ArrayIndexOutOfBoundsException e) System.out.println("Array Index Error"); catch(ArrayStoreException e) System.out.println("Wrong data type"); int y = a[1] / a[0]; System.out.println("Y = " + y);

COMMAN EXCEPTION HANDLER class Error_Handling { public static void main(String args[]) int a[ ] = {5,10}; int b = 5; try int x = a[2] / b - a[1]; } catch(ArithmeticException e) System.out.println("Division by Zero"); /*catch(ArrayIndexOutOfBoundsException e) System.out.println("Array Index Error"); }*/ catch(ArrayStoreException e) System.out.println("Wrong data type");

catch(Exception e) { System.out.println("The Producing any Runtime Error" + e.getMessage()); } int y = a[1] / a[0]; System.out.println("Y = " + y);

EXCEPTION HIERARCHY class Error_Handling { public static void main(String args[]) int a[ ] = {5,10}; int b = 5; try int x = a[2] / b - a[1]; } catch(ArithmeticException e) System.out.println("Division by Zero"); catch(Exception e) System.out.println("The Producing any Runtime Error" + e.getMessage()); /*catch(ArrayIndexOutOfBoundsException e) System.out.println("Array Index Error"); }*/

catch(ArrayStoreException e) { System.out.println("Wrong data type"); } int y = a[1] / a[0]; System.out.println("Y = " + y);

Nested try Statements class Error_Handling { public static void main(String args[]) try int a = args.length; int b = 42 / a; //If no command - line args are present, //the following statement will generate a divide - by - zero exception System.out.println("a = " + a); // nested try bloack // If one command - line arg is used, then a divide - by //- zero exception will be generated by the following code.

try { if ( a == 1) a = a / (a - a); //division by zero if(a == 2) int c[] = {1}; c[42] = 99; //generate an out - of - bounds exception } catch(ArrayIndexOutOfBoundsException e) System.out.println("Array index out - of - bounds: " + e); catch(ArithmeticException e) System.out.println("Divide by Zero: " + e);

Nested try Statements using Subroutine class Error_Handling { static void nesttry(int a) try if ( a == 1) a = a / (a - a); //division by zero if(a == 2) int c[] = {1}; c[42] = 99; //generate an out - of - bounds exception } catch(ArrayIndexOutOfBoundsException e) System.out.println("Array index out - of - bounds: " + e);

public static void main(String args[]) { try int a = args.length; int b = 42 / a; //If no command - line args are present, the //following statement will generate a divide - by - zero exception System.out.println("a = " + a); // nested try bloack // If one command - line arg is used, then a divide - by - //zero exception will be generated by the following code. nesttry(a); // Calling Static Method } catch(ArithmeticException e) System.out.println("Divide by Zero: " + e);

throw You have only been catching exceptions that are thrown by the java run – time system. However, it is possible for your program to throw an exception explicitly. Using throw statement. Syntax: throw ThrowableInstance; Here, ThrowableInstance must be an object of type Throwable or a subclass of Throwable. Simple types, such as int or char, as well as non – Throwable classes, such as String and Object, cannot be used as exception. There are two ways you can obtain a Throwable object: using a parameter into a catch clause, or creating one with the new operator.

class Error_Handling { static void display() try throw new NullPointerException("Demo"); } catch(NullPointerException e) throw e; public static void main(String args[]) display(); System.out.println("Recaught : " + e);

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. You do this by including a throws clause in the method’s declaration. A throws clause list the types of exceptions that a method might throw. This is necessary for all exceptions, except those of type Error or RuntimeException, or any of their subclasses. All other exceptions that a method can throw must be declared in the throws clause. If they are not, a compile – time error will result. type method-name (parameter-list) throws exception-list { //body of method } Here, exception – list is comma – separated list of the exceptions that a method can throw

class Error_Handling { static void throwdemo() throws IllegalAccessException System.out.println("Inside throwdemo"); } public static void main(String args[]) try throwdemo(); catch(IllegalAccessException e) System.out.println("Caught " + e);

Using finally Statement Java supports another statement known as finally statement that can be used to handle an exception that is not caught by any of the previous catch statements. finally block can be used to handle any exception generated within a try block. It may be added immediately after the try block or after the last catch block. try { //statements } catch(Exception-Type-1 e) catch(Exception-Type-2 e) ----------- catch(Exception-Type-N e) finally ------------------- try { //statements } finally -------------------

class Error_Handling { static void procA() try System.out.println("Inside ProcA"); throw new RuntimeException("demo"); } finally System.out.println("ProcA's finally"); static void procB() System.out.println("inside ProcB"); //return; System.out.println("ProcB's finally");

static void procC() { try System.out.println("inside ProcC"); } finally System.out.println("ProcC's finally"); public static void main(String args[]) procA(); catch(Exception e) System.out.println("Exception Caught"); System.out.println("Procedure A is Wind up"); procB(); procC(); } }

Java’s Built – in Exceptions The standard package java.lang, Java defines several exception classes. A few have been used by the preceding examples. The most general of these exceptions are subclasses of the standard type RuntimeException. Since java.lang is implicitly imported into all java programs, most exceptions derived from RuntimeException are automatically available. Furthermore, they need not be included in any method’s throws list. In the language of Java, these are called unchecked exceptions because the compiler does not check to see if a method handles or throws these exceptions. The other exceptions defined by java.lang that must be included in a method’s throws list if that method can generate one of these exceptions and does not handle it itself. These are called checked exceptions.

Java’s Unchecked RuntimeException Subclasses Meaning ArithmeticException Arithmetic error, such as divde – by – zero ArrayIndexOutOfBoundsException Array index is out – of – bounds. ArrayStoreException Assignment to an array element of an incompatible type. ClassCastException Invalid Cast. IllegalArgumentException Illegal argument used to invoke a method IllegalMonitoStateException Illegal Monitor Operation, such as waiting on an unlocked thread. IllegalStateException Environment or application is in incorrect state. IllegalThreadStateException Requested operation not compatible with current thread state. IndexOutOfBoundsException Some type of index is out – of – bounds NegativeArraySizeException Array Created with a negative size.

Exception Meaning NullPointerException Invalid use of a null reference. NumberFormatException Invalid conversion of a string to a numeric format. SecurityException Attempt to violate security StringIndexOutOfBounds Attempt to index outside the bounds of a string. UnsupportedOperationException An unsupported Operation was encountered.

Java’s Checked Exception Defined in java.lang Meaning ClassNotFoundException Class not found CloneNotSupportedException Attempt to clone an object that does not implement the cloneable interface. IllegalAccessException Access to a class is denied InstantiationException Attempt to create an object of an abstract class or interface InterruptedException One thread has been interrupted by another thread. NoSuchFieldException A requested field does not exist. NoSuchMethodException A requested method does not exist.

throw new Throwable_subclass; Throwing our own Exceptions There may be times when we would like to throw our own exceptions. We can do this by using the keyword throw as follows: throw new Throwable_subclass; Example: throw new ArithmeticException(); throw new NumberFormatException(); Note: Exception is subclass of Throwable and therefore MyException is a subclass of Throwable class. An object of a class that extends Throwable can be thrown and caught

import java.lang.Exception; class MyException extends Exception { MyException(String message) super(message); } class Exception_Handling public static void main(String args[]) int x = 5, y = 1000; try float z = (float) x / (float) y; if (z < 0.01) throw new MyException("Number is too small");

catch(MyException e) { System.out.println("Caught my exception"); System.out.println(e.getMessage()); } finally System.out.println("I am always here");

Using Exceptions Exception handling provides a powerful mechanism for controlling complex programs that have many dynamic run – time characteristics. It is important to think of try, throw and catch as clean ways to handle errors and unusual boundary conditions in your program’s logic. If you are like most programmers, then you probably are used to returning an error code when a method fails. When you are programming in Java, you should break this habit. When a method can fail, have it throw an exception. This is a cleaner way to handle failure modes. One last point: Java’s Exception – handling statements should not be considered a general mechanism for nonlocal branching. If you do so, it will only confuse your code and make it hard to maintain.