Handling Exceptions in java. Exception handling blocks try { body-code } catch (exception-classname variable-name) { handler-code }

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

Exceptions Session 21. Memory Upload Creating Exceptions Using exceptions to control object creation and validation.
Exceptions: when things go wrong. Various sources of error public static doSomething() { int i = 3.0; while(!done); { int i = false } ) Syntactic errors.
Yoshi
Lecture 9. 2 Exception  An exception is a unusual, often unpredictable event, detectable by software or hardware, that requires special processing occurring.
Exceptions Ensuring program reliability. Program correctness The term program correctness refers to a program’s working as advertised; that is, it produces.
Introduction to Exceptions in Java. 2 Runtime Errors What are syntax errors? What are runtime errors? Java differentiates between runtime errors and exceptions.
COMP 121 Week 5: Exceptions and Exception Handling.
Java I/O Java I/O is based on input streams and output streams. All input and output are defined in the Java IO package. 1.
Exception Handling Yaodong Bi Exception Handling Java exception handling Try blocks Throwing and re-throwing an exception Catching an.
Lesson 16 Exceptions Lesson Exceptions1. Murphy’s Law Anything that can go wrong will go wrong Lesson Exceptions2.
Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.
Exception Handling Topics We will discuss the following main topics: – Handling Exceptions – Throwing Exceptions – More about Input/Output Streams.
1 / 89 COP 3503 FALL 2012 SHAYAN JAVED LECTURE 11 Programming Fundamentals using Java 1.
EXCEPTIONS Def: An exception is a run-time error. Examples include: attempting to divide by zero, or manipulate invalid data.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 8 Exception Handling Sections 1-5, 7.
1 Why do we need exceptions? In C, return variables must be used to indicate errors: if((fd = fopen(path,...)) == -1){ if(errno==a){...} else if(errno==b){...}
Exceptions Used to signal errors or unexpected situations to calling code Should not be used for problems that can be dealt with reasonably within local.
Exceptions and Assertions Recitation – 03/13/2009 CS 180 Department of Computer Science, Purdue University.
Java Exception Handling ● Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions: – Examples:
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 8 Exception Handling Sections 1-5, 7.
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.
CS203 Java Object Oriented Programming Errors and Exception Handling.
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.
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.
MT311 Java Application Development and Programming Languages Li Tak Sing( 李德成 )
06 Exception Handling. 2 Contents What is an Exception? Exception-handling in Java Types of Exceptions Exception Hierarchy try-catch()-finally Statement.
Exception Handling in Java Exception Handling Introduction: After completing this chapter, you will be able to comprehend the nature and kinds.
CMSC 202 Exceptions. Aug 7, Error Handling In the ideal world, all errors would occur when your code is compiled. That won’t happen. Errors which.
CS 2511 Fall  Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions:  Examples: Out.
Class Design: Handling Errors Reading: 2 nd Ed: Chapter 15 3 rd Ed: Chapter 11 Exercises 2 nd Ed: P15.5, P15.6 (Hint: look at documentation for Scanner.
Java I/O Java I/O is based on input streams and output streams. All input and output are defined in the Java IO package. 1.
Exceptions CSC 171 FALL 2004 LECTURE 24. READING Read Horstmann Chapter 14 This course covered Horstmann Chapters
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.
Programming and Problem Solving With Java Copyright 1999, James M. Slack Exceptions Handling Exceptions with try and catch The finally-block The throws.
Exceptions and Assertions Chapter 15 – CSCI 1302.
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.
EXCEPTIONS There's an exception to every rule.. 2 Introduction: Methods  The signature of a method includes  access control modifier  return type 
MIT AITI 2004 – Lecture 14 Exceptions Handling Errors with 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.
Today’s lecture Review of chapter 8 Go over examples.
Lecture10 Exception Handling Jaeki Song. Introduction Categories of errors –Compilation error The rules of language have not been followed –Runtime error.
And other languages…. must remember to check return value OR, must pass label/exception handler to every function Caller Function return status Caller.
ECE122 L23: Exceptions December 6, 2007 ECE 122 Engineering Problem Solving with Java Lecture 24 Exceptions.
Exceptions and Error Handling. Exceptions Errors that occur during program execution We should try to ‘gracefully’ deal with the error Not like this.
Lecture 5: Exception Handling and Text File I/O Michael Hsu CSULA.
Java Exceptions a quick review….
Exceptions In this lecture:
Exceptions: When things go wrong
Chapter 10 – Exception Handling
MIT AITI 2003 Lecture14 Exceptions
Java Programming Language
Exceptions, Interfaces & Generics
Introduction Exception handling Exception Handles errors
Advanced Programming Behnam Hatami Fall 2017.
Exception Handling in Java
Exception Handling and Reading / Writing Files
Exception Handling in Java
Intro to Exceptions (c) Eraj Basnayake
Java Exceptions Dan Fleck CS211.
Java Basics Exception Handling.
CMSC 202 Exceptions.
Exception Handling.
Presentation transcript:

Handling Exceptions in java

Exception handling blocks try { body-code } catch (exception-classname variable-name) { handler-code }

Exceptions An exception is an event that occurs during the execution of a program that disrupts the normal flow –a signal that some sort of exception condition or error has occurred Exceptions must be detected and handled so the program can continue if at all possible –To throw an exception is to signal an exceptional condition –to catch an exception is to handle it An exception is an object

throw signals that some sort of exceptional condition or error has occurred example, in class ArithmeticUtilities public static double factorial(int x){ if (x =0”); double fact; for (fact=1.0; x>1; fact*=x, x--); return fact; }

What happens exceptions… When a throw statement is executed… –normal program execution stops –it searches for an exception handler to catch the exception –if the exception is caught (ie. handled) execution continues at the statement after the handler code –if the exception is not caught, the interpreter looks for a handler in the calling method and continues searching up the Java call stack –if the exception is never caught, the JRE prints an error msg, a stack trace and exits

Exception Handlers to detect and handle exceptions use try { … } catch (SomeException e1) { … } finally{ … } can have >1 catch blocks block of code where an exception may occur, i.e. be thrown block(s) of code where one or more exceptions are handled block of code to clean up after the code in the try clause

Exceptions All exceptions have data - a String field that stores an error msg set when the exception is created e.g. accessed by a getMessage() method e.g. in the method that invokes the factorial() method if (x =0”); catch (IllegalArgumentException e){ System.out.println(“Error: + ”e.getMessage()); }

Checked/Unchecked Unchecked exceptions can be thrown at any time by virtually any method –e.g OutOfMemoryError, NullPointerException Checked exceptions occur in specific, well- defined circumstances –Well written applications should anticipate and cater for these –e.g.FileNotFoundException, EOFException IllegalArgumentException

Checked Exceptions If a method invokes another method that “throws” a checked exception it must either –include exception handling code to handle the exception –use throws in the method declaration to declare that this method also throws that exception e.g. (though not necessarily a good idea!) a method that invokes factorial but does not handle the IllegalArgumentException void myMethod() throws IllegalArgumentException {... ArithmeticUtilities.factorial(5);... }

User Defined Exceptions To define a new exception, create a subclass of Exception Include two constructors, –the default constructor –one to allow for an error specific message class MyException extends Exception { MyException(){ } MyException(String s){ super(s); } }

User Defined Exceptions When your error occurs Handle your exception throw new MyException(); throw new MyException(“error specific string”); catch (MyException e){... }

User defined exceptions public class InvalidAgeException extends Exception { private int age; public InvalidAgeException {}; public InvalidAgeException(int age) { this.age = age; } public String toString() { return "Age cannot be negative" + " " +age ; }..

Using the user defined exception.... In another class.. if (age < 0){ throw new InvalidAgeException(age); }else{ System.out.println("Age entered is " + age); } static int getAge() { return -10; }

So remember.. Try/ Catch/ Finally… blocks The try{}Catch{} structure should be used when it is possible that your method/code will fail. if you use a method for input that requires an int, and the user enters a double, it will fail, throwing an exception. Methods like that need to be in try/catch structures.

User Defined Exceptions At first glance, this function seems simple enough, but it ignores all the following potential errors. What happens if the file can't be opened? What happens if the length of the file can't be determined? What happens if enough memory can't be allocated? What happens if the read fails? What happens if the file can't be closed?

User Defined Exceptions readFile { try { open the file; determine its size; allocate that much memory; read the file into memory; close the file; } catch (fileOpenFailed) { doSomething; } catch (sizeDeterminationFailed) { doSomething; } catch (memoryAllocationFailed) { doSomething; } catch (readFailed) { doSomething; } catch (fileCloseFailed) { doSomething; } }