Exception-Handling Fundamentals  A Java exception is an object that describes an exceptional (that is, error) condition that has occurred in a piece of.

Slides:



Advertisements
Similar presentations
Exceptions CSE301 University of Sunderland Harry Erwin, PhD.
Advertisements

Topics Introduction Types of Errors Exceptions Exception Handling
Lecture 23 Input and output with files –(Sections 2.13, 8.7, 8.8) Exceptions and exception handling –(Chapter 17)
Exception Handling Chapter 15 2 What You Will Learn Use try, throw, catch to watch for indicate exceptions handle How to process exceptions and failures.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 15: Exception Handling.
Index Exception handling Exception In Java Exception Types
Chapter 16: Exception Handling C++ Programming: From Problem Analysis to Program Design, Fifth Edition.
Objectives In this chapter you will: Learn what an exception is Learn how to handle exceptions within a program See how a try / catch block is used to.
Exception Handling Yaodong Bi Exception Handling Java exception handling Try blocks Throwing and re-throwing an exception Catching an.
Exceptions Any number of exceptional circumstances may arise during program execution that cause trouble import java.io.*; class IOExample { public static.
 2002 Prentice Hall, Inc. All rights reserved. Chapter 14 – Exception Handling Outline 14.1 Introduction 14.2 When Exception Handling Should Be Used 14.3.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 16: Exception Handling.
Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.
Sadegh Aliakbary Sharif University of Technology Fall 2010.
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. 2 Examples for Exception?... An exception is an abnormal condition that arises in a code sequence at run time (Run time error). In other computer languages.
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.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 8 Exception Handling Sections 1-5, 7.
Chapter 8 Exceptions. Topics Errors and Exceptions try-catch throwing Exceptions Exception propagation Assertions.
Intermediate Java II Sakir YUCEL MISM/MSIT Carnegie Mellon University Lecture: Exception Handling Slides adapted from Prof. Steven Roehrig.
1 Exception Handling  Introduction to Exceptions  How exceptions are generated  A partial hierarchy of Java exceptions  Checked and Unchecked Exceptions.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 8 Exception Handling Sections 1-5, 7.
Chapter 11: Handling Exceptions and Events J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Fourth.
Exception Error handling. Exception 4 n An unusual occurrence during program execution that requires immediate handling n Errors are the most common type.
1 Lecture#8: EXCEPTION HANDLING Overview l What exceptions should be handled or thrown ? l The syntax of the try statement. l The semantics of the try.
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.
Java Software Solutions Foundations of Program Design Sixth Edition
What is an exception? An exception is: – an event that interrupts the normal processing of the program. –an error condition that violates the semantic.
Exception Handling. Exceptions and Errors When a problem encounters and unexpected termination or fault, it is called an exception When we try and divide.
Object Oriented Programming
06 Exception Handling. 2 Contents What is an Exception? Exception-handling in Java Types of Exceptions Exception Hierarchy try-catch()-finally Statement.
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.
Slides Credit Umair Javed LUMS Web Application Development.
Exception Handling in JAVA. Introduction Exception is an abnormal condition that arises when executing a program. In the languages that do not support.
Chapter 14: Exception Handling. Objectives In this chapter, you will: – Learn what an exception is – Learn how to handle exceptions within a program –
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.
BIO Java 1 Exception Handling Aborting program not always a good idea – can’t lose messages – E-commerce: must ensure correct handling of private.
Chapter 12 Handling Exceptions and Events. Chapter Objectives Learn what an exception is Become aware of the hierarchy of exception classes Learn about.
Sheet 3 HANDLING EXCEPTIONS Advanced Programming using Java By Nora Alaqeel.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 11 Handling Exceptions and Events.
Programming and Problem Solving With Java Copyright 1999, James M. Slack Exceptions Handling Exceptions with try and catch The finally-block The throws.
Exception Handling in Java Topics: Introduction Errors and Error handling Exceptions Types of Exceptions Coding Exceptions Summary.
Chapter 15: Exception Handling C++ Programming: Program Design Including Data Structures, Fifth Edition.
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.
Copyright © Curt Hill Error Handling in Java Throwing and catching exceptions.
Exceptions Handling Prepared by: Ligemm Mae del Castillo.
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:
Exceptions and Error Handling. Exceptions Errors that occur during program execution We should try to ‘gracefully’ deal with the error Not like this.
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.
CSE 332: C++ Exceptions Motivation for C++ Exceptions Void Number:: operator/= (const double denom) { if (denom == 0.0) { // what to do here? } m_value.
Chapter 10 – Exception Handling
Java Programming Language
COMPSCI 230 S Programming Techniques
EXCEPTION HANDLING OR ERROR HANDLING.
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.
Exception Handling.
Java Programming: From Problem Analysis to Program Design, 4e
Presentation transcript:

Exception-Handling Fundamentals  A Java exception is an object that describes an exceptional (that is, error) condition that has occurred in a piece of code.  When an exceptional condition arises, an object representing that exception is created and thrown in the method that caused the error. That method may choose to handle the exception itself, or pass it on. Either way, at some point, the exception is caught and processed.

Contd…..  Exceptions can be generated by the Java run-time system, or they can be manually generated by your code.  Exceptions thrown by Java relate to fundamental errors that violate the rules of the Java language or the constraints of the Java execution environment. Manually generated exceptions are typically used to report some error condition to the caller of a method.  Java exception handling is managed via five keywords: try, catch, throw, throws, and finally.

Exception-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 }

Exception Types  All exception types are subclasses of the built-in class Throwable. Thus, Throwable is at the top of the exception class hierarchy.  Immediately below Throwable are two subclasses that partition exceptions into two distinct branches. One branch is headed by Exception.  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.

 There is an important subclass of Exception, called RuntimeException.  Exceptions of this type are automatically defined for the programs that you write and include things such as division by zero and invalid array indexing.  The other branch is topped by Error, which defines exceptions that are not expected to be caught under normal circumstances by your program.  Exceptions of type Error are used by the Java run-time system to indicate errors having to do with the run-time environment, itself. Stack overflow is an example of such an error.

Uncaught Exceptions Before you learn how to handle exceptions in your program, it is useful to see what happens when you don’t handle them. This small program includes an expression that intentionally causes a divide-by-zero error. Class error1 { public static void main( String args[ ]) { int a=10; int b=5; int c=5; int x=a/(b-c); System.out.println(“x” +x); int y= a/(b+c); System.out.println(“y” +y); }

Using try-catch block Class error2 { public static void main( String args[ ]) {int a=10; int b=5; int c=5; int x, y; try { x= a/( b-c); }

Catch (AirthmeticException e) { System.out.println(“division by Zero”); } y=a/(b+c); System.out.println(“y” +y); }

Why do I have put an f after a floating point constants The f suffix directs the compiler to create a float value a sequence of characters representing a floating point number (a float literal) – otherwise the compiler would by default create either a double value or an int value.

Multiple catch Clauses In some cases, more than one exception could be raised by a single piece of code. To handle this type of situation, you can specify two or more catch clauses, each catching a 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.

Multiple Catch Statements try {statement; // generates an exception } catch (Exception_type-1 e) { Statement; } catch (Exception_type-2 e) { Statement; } Catch (Exception_type-3 e) { Statement;}

Multiple Catch statements class multicatch { public static void main( String args[ ]) int a [ ] = {5, 10}; int b=5; try { int x= a[2] /b-a[1]; } catch( ArithmaticException e) { System.out.println(“Division by Zero”); }

catch( ArrayIndexOutOfBoundsException e) { System.out.println(“array index array”); } catch( ArrayStoreException e) { System.out.println(“ Wrong Data type”); }

Nested try statement The try statement can be nested. That is, 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 handler for a particular exception, the stack is unwound and the next try statement’s catch handlers are inspected for a match. This continues until one of the catch statements succeeds, or until all of the nested try statements are exhausted. If no catch statement matches, then the Java run-time system will handle the exception.

Nested try statements class nestTry { public static void main( String args[ ]) try { int a= args.length; int b= 42/a; System.out.println(“ a” +a); try { if(a==1) a=a/(a-a);

Contd…… If(a==2) { int c[ ]= {1}; c[42]=99; } catch(ArrayIndexOutOfBoundsException e) { System.out.println(“ Array index out of bounds” +e) } Catch((AirthmaticException e) { System.out.println(“ divided by 0:” +e); }

throw statement So far, We have only been catching exceptions that are thrown by the java run-time system. However, it is possible for your program to throw statement. The syntax is: throw ThrowableInstance ; Throwableinstance must be an object of type throwable or subclass of Throwable.

Example of throw statement Class throwdemo { static void demoproc() { try { throw new NullPointerException(“demo”) } Catch(NullPointerException e){ System.out.println(“caught inside demoproc”); Throw e; // rethrow the exception }

Contd……….. public static void main( String s[ ]) { try { demoproc(); } catch(NullPointerException e) { System.out.println(“Recaught” +e); }

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

Finally statement Finally statement is used to handle an exception that is not caught by any of the 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.

Syntax of finally statement try { ………. { ………. ………. ………. } } finally { catch ( ….) ………. { ……….. } } finally{ ……… }

Use of Interface 1. To incorporate multiple inheritence in Java Application. 2. To Develop Distributed applications.

Difference between java and java script Java language can stand on its own and creates "standalone" applications while JavaScript must be placed inside an HTML document to function.applications Java must be compiled into what is known as a "machine language" before it can be run. You can alter JavaScript that are in an HTML document after it runs and run it again and again. If you alter java program you need to compile it again before run.languageJavaScript

Creating Your Own Exception Subclasses Although Java’s built-in exceptions handle most common errors, you will probably want to create your own exception types to handle situations specific to your applications. This is quite easy to do: just define a subclass of Exception. Your subclasses don’t need to actually implement anything—it is their existence in the type system that allows you to use them as exceptions.

Creating and throwing your own exception import java.lang.Exception; class myexception extends Exception { myexception(String message) { super(message); } class testmyexcp {public static void main(Strings args[ ]) {int x=5, y=1000; try { float z=(float) x/ (float) y; if( z < 0.01) {

Contd…. 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 m always here”); } } } }

Java’s Built-in Exceptions