Exception Handling in Java Topics: Introduction Errors and Error handling Exceptions Types of Exceptions Coding Exceptions Summary.

Slides:



Advertisements
Similar presentations
Exceptions Chapter Throwing and Catching Exceptions When a program runs into a problem that it cannot handle, it throws an exception. Exceptions.
Advertisements

Yoshi
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.
Introduction to Exceptions in Java. 2 Runtime Errors What are syntax errors? What are runtime errors? Java differentiates between runtime errors and exceptions.
Errors and Exceptions The objectives of this chapter are: To understand the exception handling mechanism defined in Java To explain the difference between.
COMP 121 Week 5: Exceptions and Exception Handling.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 13 Exception Handling.
Exceptions and Exception Handling Carl Alphonce CSE116 March 9, 2007.
Exception Handling Yaodong Bi Exception Handling Java exception handling Try blocks Throwing and re-throwing an exception Catching an.
MIT-AITI Lecture 14: Exceptions Handling Errors with Exceptions Kenya 2005.
Exception Handling 1 CISC6795, Spring Introduction 2 Exception – an indication of a problem that occurs during a program’s execution, for examples:
Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.
1 / 89 COP 3503 FALL 2012 SHAYAN JAVED LECTURE 11 Programming Fundamentals using Java 1.
Understand Error Handling Software Development Fundamentals LESSON 1.4.
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.
11-Jun-15 Exceptions. 2 Errors and Exceptions An error is a bug in your program dividing by zero going outside the bounds of an array trying to use a.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 17 Exceptions and.
16-Jun-15 Exceptions. Errors and Exceptions An error is a bug in your program dividing by zero going outside the bounds of an array trying to use a null.
Exceptions in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Exceptions. Errors and Exceptions An error is a bug in your program –dividing by zero –going outside the bounds of an array –trying to use a null reference.
Chapter 11: Handling Exceptions and Events J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Fourth.
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.
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.
CIS3023: Programming Fundamentals for CIS Majors II Summer 2010 Ganesh Viswanathan Exception Handling in Java Course Lecture Slides 7 th July 2010 “ Admitting.
Java Software Solutions Foundations of Program Design Sixth Edition
Preventing and Correcting Errors
Exception Handling. Exceptions and Errors When a problem encounters and unexpected termination or fault, it is called an exception When we try and divide.
Chapter 13 Exception Handling F Claiming Exceptions F Throwing Exceptions F Catching Exceptions F Rethrowing Exceptions  The finally Clause F Cautions.
June 14, 2001Exception Handling in Java1 Richard S. Huntrods June 14, 2001 University of Calgary.
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
Java Programming Exceptions Handling. Topics: Learn about exceptions Try code and catch Exceptions Use the Exception getMessage() method Throw and catch.
CIS 270—Application Development II Chapter 13—Exception Handling.
Chapter 12: 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 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.
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.
Exceptions and Assertions Chapter 15 – CSCI 1302.
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.
Copyright © Curt Hill Error Handling in Java Throwing and catching exceptions.
1 Exceptions. 2 Syntax Errors, Runtime Errors, and Logic Errors syntax errors, runtime errors, and logic errors You learned that there are three categories.
Exceptions Lecture 11 COMP 401, Fall /25/2014.
Lecture10 Exception Handling Jaeki Song. Introduction Categories of errors –Compilation error The rules of language have not been followed –Runtime error.
Exception. Agenda Exception. Handling Exceptions. The finally Clause.
Exception and Exception Handling. Exception An abnormal event that is likely to happen during program is execution Computer could run out of memory Calling.
Throw, Throws & Try-Catch Statements Explanations and Pictures from: Reference:
ECE122 L23: Exceptions December 6, 2007 ECE 122 Engineering Problem Solving with Java Lecture 24 Exceptions.
Introduction to Exceptions in Java CS201, SW Development Methods.
Lecture 5: Exception Handling and Text File I/O Michael Hsu CSULA.
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.
Eighth Lecture Exception Handling in Java
Tirgul 13 Exceptions 1.
Exceptions 10-Nov-18.
Chapter 12 Exception Handling
Exception Handling Chapter 9 Edited by JJ.
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.
Chapter 12 Exception Handling and Text IO Part 1
Exceptions 10-May-19.
Java Basics Exception Handling.
Exception Handling.
Presentation transcript:

Exception Handling in Java Topics: Introduction Errors and Error handling Exceptions Types of Exceptions Coding Exceptions Summary

Introduction Users have high expectations for the code we produce. Users will use our programs in unexpected ways. Due to design errors or coding errors, our programs may fail in unexpected ways during execution It is our responsibility to produce quality code that does not fail unexpectedly. Consequently, we must design error handling into our programs.

Errors and Error Handling An Error is any unexpected result obtained from a program during execution. Unhandled errors may manifest themselves as incorrect results or behavior, or as abnormal program termination. Errors should be handled by the programmer, to prevent them from reaching the user. Some typical causes of errors: Memory errors (i.e. memory incorrectly allocated, memory leaks, “null pointer”) File system errors (i.e. disk is full, disk has been removed) Network errors (i.e. network is down, URL does not exist) Calculation errors (i.e. divide by 0)

Errors and Error Handling More typical causes of errors: Array errors (i.e. accessing element –1) Conversion errors (i.e. convert ‘q’ to a number) Can you think of some others? Traditional Error Handling 1. Every method returns a value (flag) indicating either success, failure, or some error condition. The calling method checks the return flag and takes appropriate action. Downside: programmer must remember to always check the return value and take appropriate action. This requires much code (methods are harder to read) and something may get overlooked.

Errors and Error Handling Traditional Error Handling Where used: traditional programming languages (i.e. C) use this method for almost all library functions (i.e. fopen() returns a valid file or else null) 2. Create a global error handling routine, and use some form of “jump” instruction to call this routine when an error occurs. Downside: “jump” instruction (GoTo) are considered “bad programming practice” and are discouraged. Once you jump to the error routine, you cannot return to the point of origin and so must (probably) exit the program.

Errors and Error Handling Traditional Error Handling Where used: many older programming texts (C, FORTRAN) recommended this method to programmers. Those who use this method will frequently adapt it to new languages (C++, Java).

Errors and Error Handling Exceptions – a better error handling Exceptions are a mechanism that provides the best of both worlds. Exceptions act similar to method return flags in that any method may raise and exception should it encounter an error. Exceptions act like global error methods in that the exception mechanism is built into Java; exceptions are handled at many levels in a program, locally and/or globally.

Exceptions What are they? An exception is a representation of an error condition or a situation that is not the expected result of a method. Exceptions are built into the Java language and are available to all program code. Exceptions isolate the code that deals with the error condition from regular program logic.

Exceptions How are they used? Exceptions fall into two categories: Checked Exceptions Unchecked Exceptions Checked exceptions are inherited from the core Java class Exception. They represent exceptions that are frequently considered “non fatal” to program execution Checked exceptions must be handled in your code, or passed to parent classes for handling.

Exceptions How are they used? Unchecked exceptions represent error conditions that are considered “fatal” to program execution. You do not have to do anything with an unchecked exception. Your program will terminate with an appropriate error message. Examples: Checked exceptions include errors such as “array index out of bounds”, “file not found” and “number format conversion”. Unchecked exceptions include errors such as “null pointer”.

Exceptions How do you handle exceptions? Exception handling is accomplished through the “try – catch” mechanism, or by a “throws” clause in the method declaration. For any code that throws a checked exception, you can decide to handle the exception yourself, or pass the exception “up the chain” (to a parent class).

Exceptions How do you handle exceptions? To handle the exception, you write a “try-catch” block. To pass the exception “up the chain”, you declare a throws clause in your method or class declaration. If the method contains code that may cause a checked exception, you MUST handle the exception OR pass the exception to the parent class (remember, every class has Object as the ultimate parent)

Coding Exceptions Try-Catch Mechanism Wherever your code may trigger an exception, the normal code logic is placed inside a block of code starting with the “try” keyword: After the try block, the code to handle the exception should it arise is placed in a block of code starting with the “catch” keyword.

Coding Exceptions Try-Catch Mechanism You may also write an optional “finally” block. This block contains code that is ALWAYS executed, either after the “try” block code, or after the “catch” block code. Finally blocks can be used for operations that must happen no matter what (i.e. cleanup operations such as closing a file)

Coding Exceptions Example try { … normal program code } catch(Exception e) { … exception handling code }

Coding Exceptions Passing the exception In any method that might throw an exception, you may declare the method as “throws” that exception, and thus avoid handling the exception yourself Example public void myMethod throws IOException { … normal code with some I/O }

Coding Exceptions Types of Exceptions All checked exceptions have class “Exception” as the parent class. You can use the actual exception class or the parent class when referring to an exception Where do you find the exception classes? Reference books such as “Java in a Nutshell” (O’Reilly, 2001), or the Java Documentation.

Coding Exceptions Types of Exceptions Examples: public void myMethod throws Exception { public void myMethod throws IOException { try { … } catch (Exception e) { … } try { … } catch (IOException ioe) { … } 1. Demonstration of an unchecked exception (NullPointerException) 2. Demonstration of checked exceptions: Passing a DivideByZeroException Handling a DivideByZeroException

Summary Exceptions are a powerful error handling mechanism. Exceptions in Java are built into the language. Exceptions can be handled by the programmer (try-catch), or handled by the Java environment (throws).

Nested try Statements The try statement can be nested. That is, a try statement can be inside the block of another try.

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); // division by zero if(a==2) { int c[ ] = { 1 }; c[42] = 99; } catch(ArrayIndexOutOfBoundsException e) { System.out.println("Array index out-of-bounds: " + e); } catch(ArithmeticException e) { System.out.println("Divide by 0: " + e); }

Normal program execution is immediately branched when an exception is thrown. Checked exceptions must be caught or forwarded. This can be done in a try... catch statement or by defining the exception in the method definition. The exception is caught by the first catch block whose associated exception class matches the class or a superclass of the thrown exception. If no matching catch block is found in the exception chain, the thread containing the thrown exception is terminated. The finally block after a try... catch statement is executed regardless whether an exception is caught or not. Returning within a finally block breaks the exception chain to the invoker even for uncaught exceptions.

Exceptions in Java Exceptions are nothing but some anomalous conditions that occur during the execution of the program. Exceptions are the conditions or typically an event which may interrupt the normal flow of the program's instructions. Exceptions in Java Exception Classes The hierarchy of exception classes commence from Throwable class which is the base class in java.lang. This class can be instantiated and thrown by the program. The Throwable class is further divided into two subclasses :- Exception Classes Catching and Handling Exceptions The three exception handler components are used to catch and handle the exceptions. These are try, catch and finally clause. The mechanism to catch an exception in Java is to use try and catch block. Catching and Handling Exceptions

How to Throw Exceptions Before catching an exception it is must to be thrown first. This means that there should be a code somewhere in the program that could catch the exception. How to Throw Exceptions Handling Multiple Catch Clauses In java when we handle the exceptions then we can have multiple catch blocks for a particular try block to handle many different kind of exceptions that may be generated while running the program. Handling Multiple Catch Clauses Nested Try-Catch Blocks In Java we can have nested tryand catch blocks. It means that, a try statement can be inside the block of another try. Nested Try-Catch Blocks Catching Normal Exceptions The exceptions that are generated by methods are referred to as normal exceptions. We have already learned that to catch an exception we use try and catch block. Catching Normal Exceptions

Making Custom (User Defined) Exceptions If you encounter a situation where none of those exception describe your exception accurately or if you can't find the appropriate exception in the Java API, you can code a class that defines an exception that is more appropriate Making Custom (User Defined) Exceptions What are Chained Exceptions Chained exceptions are the exceptions which occur one after another i.e. most of the time to response to an exception is given by an application by throwing another exception. What are Chained Exceptions How to Print a Stack Trace Message Instead of this this method you can get more information about the error process if you print a stack trace from the exception using the printStackTrace() method that prints the stack trace to the console How to Print a Stack Trace Message