Exceptions and Error Handling. Exceptions Errors that occur during program execution We should try to ‘gracefully’ deal with the error Not like this.

Slides:



Advertisements
Similar presentations
Pearson Education, Inc. All rights reserved. 1.. Exception Handling.
Advertisements

Exceptions: when things go wrong. Various sources of error public static doSomething() { int i = 3.0; while(!done); { int i = false } ) Syntactic errors.
Exceptions & exception handling Use sparingly. Things you can do with exceptions: 1. Define a new exception class. 2. Create an exception instance. 3.
Lecture 23 Input and output with files –(Sections 2.13, 8.7, 8.8) Exceptions and exception handling –(Chapter 17)
CS102--Object Oriented Programming
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.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 13 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.
SE-1020 Dr. Mark L. Hornick 1 More Exception Handling and Throwing Exceptions.
Exception Handling1. 2 Exceptions  Definition  Exception types  Exception Hierarchy  Catching exceptions  Throwing exceptions  Defining exceptions.
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 10 GEORGE KOUTSOGIANNAKIS Copyright: 2014 Illinois Institute of Technology/ George Koutsogiannakis 1.
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.
Exceptions Briana B. Morrison CSE 1302C Spring 2010.
Testing and Error Handling Intro to Java. Testing We test to try and make sure our programs work correctly and have no bugs If we have access to the code,
MSc IT Programming Methodology (2). THROWS an EXCEPTION Errors?
File I/O and Exceptions File I/O Exceptions Throwing Exceptions Try statement and catch / finally clauses Checked and unchecked exceptions Throws clause.
Lecture 27 Exceptions COMP1681 / SE15 Introduction to Programming.
Exceptions CIS 304 Intermediate Java Programming for Business.
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.
1 Exception Handling (in a nutshell). 2 Motivations When a program runs into a runtime error, the program terminates abnormally. How can you handle the.
1 Exception Handling  Introduction to Exceptions  How exceptions are generated  A partial hierarchy of Java exceptions  Checked and Unchecked Exceptions.
Chapter 11: Handling Exceptions and Events J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Fourth.
Exception Handling Recitation – 10/(23,24)/2008 CS 180 Department of Computer Science, Purdue University.
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.
What is an exception? An exception is: – an event that interrupts the normal processing of the program. –an error condition that violates the semantic.
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.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 18 Exception Handling.
06 Exception Handling. 2 Contents What is an Exception? Exception-handling in Java Types of Exceptions Exception Hierarchy try-catch()-finally Statement.
Java Programming Exception Handling. The exception handling is one of the powerful mechanism provided in java. It provides the mechanism to handle the.
Exceptions. Exception Abnormal event occurring during program execution Examples –Manipulate nonexistent files FileReader in = new FileReader("mumbers.txt“);
Exception Handling in JAVA. Introduction Exception is an abnormal condition that arises when executing a program. In the languages that do not support.
Spring 2008 Mark Fontenot CSE 1341 Principles of Computer Science I Note Set 10.
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 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.
Exceptions By the end of this lecture you should be able to: explain the term exception; distinguish between checked and unchecked exception classes in.
1 Exception handling in Java Reading for this lecture: Weiss, Section 2.5 (exception handling), p. 47. ProgramLive, chapter 10. I need to know whether.
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 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.
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.
Throw, Throws & Try-Catch Statements Explanations and Pictures from: Reference:
Exceptions an unusual condition – e.g. division by zero – e.g. file doesn't exist – e.g. illegal type – etc. etc… typically a run-time error – i.e. during.
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.
Chapter 10 – Exception Handling
OBJECT ORIENTED PROGRAMMING II LECTURE 10 GEORGE KOUTSOGIANNAKIS
MIT AITI 2003 Lecture14 Exceptions
Introduction to Exceptions in Java
Introduction to Exceptions in Java
CS102 – Exceptions David Davenport Latest: May 2015
Testing and Exceptions
Handling Exceptions.
Exception Handling.
Fundamental Error Handling
Exception Handling in Java
Web Design & Development Lecture 7
Chapter 13 Exception Handling
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.
Chapter 12 Exception Handling and Text IO Part 1
Java Basics Exception Handling.
Java Programming: From Problem Analysis to Program Design, 4e
Presentation transcript:

Exceptions and Error Handling

Exceptions Errors that occur during program execution We should try to ‘gracefully’ deal with the error Not like this

When an error occurs You can deal with it, or you can ‘pass the buck’ and let the caller handle the exception

Try-Catch Blocks try { // some stuff that may cause an error } catch (the first error type) { // do something about this specific error type } catch (another error type) { // do something about this second error type }

Try-Catch Blocks A statement in a try { } block throws an exception! Let’s divide by zero Control immediately passes to the catch block for the type of exception thrown The catch code executes, and then control goes to the code after the last catch block try appropriate catch code after all catches

Exception Handling When an exception occurs… If it is not handled by the method… It goes to the caller. If it’s not handled by the method… It goes to the caller …and so on until it gets to main

Example class ExceptionExample { private int[] myArray; public ExceptionExample() { myArray = new int[10]; } public void causeTrouble() { reallyCauseTrouble(); } public void reallyCauseTrouble() { myArray[10] = 88; } public class TestException { public static void main (String [] args) { ExceptionExample e1 = new ExceptionExample(); e1.causeTrouble(); } Oops! Array out of bounds… but I don’t handle exceptions! Oops! Array out of bounds… but I don’t handle exceptions!

Example class ExceptionExample { private int[] myArray; public ExceptionExample() { myArray = new int[10]; } public void causeTrouble() { reallyCauseTrouble(); } public void reallyCauseTrouble() { myArray[10] = 88; } public class TestException { public static void main (String [] args) { ExceptionExample e1 = new ExceptionExample(); e1.causeTrouble(); } So return to my caller and see if they handle exceptions (have a catch block)… not here either

Example class ExceptionExample { private int[] myArray; public ExceptionExample() { myArray = new int[10]; } public void causeTrouble() { reallyCauseTrouble(); } public void reallyCauseTrouble() { myArray[10] = 88; } public class TestException { public static void main (String [] args) { ExceptionExample e1 = new ExceptionExample(); e1.causeTrouble(); } So return to my caller and see if they handle exceptions (have a catch block)… not here either

Example class ExceptionExample { private int[] myArray; public ExceptionExample() { myArray = new int[10]; } public void causeTrouble() { reallyCauseTrouble(); } public void reallyCauseTrouble() { myArray[10] = 88; } public class TestException { public static void main (String [] args) { ExceptionExample e1 = new ExceptionExample(); e1.causeTrouble(); } But this is the main method, so the program terminates with an ugly error message.

Example class ExceptionExample { private int[] myArray; public ExceptionExample() { myArray = new int[10]; } public void causeTrouble() { reallyCauseTrouble(); } public void reallyCauseTrouble() { myArray[10] = 88; } public class TestException { public static void main (String [] args) { ExceptionExample e1 = new ExceptionExample(); e1.causeTrouble(); } stack trace: Java.lang.ArrayIndexOutOfBoundsException: 10 at ExceptionExample.reallyCauseTrouble( ) at EceptionExample.causeTrouble( ) at TestException.main( ) stack trace: Java.lang.ArrayIndexOutOfBoundsException: 10 at ExceptionExample.reallyCauseTrouble( ) at EceptionExample.causeTrouble( ) at TestException.main( )

Example class ExceptionExample { private int[] myArray; public void reallyCauseTrouble() { try { myArray[10] = 88; } catch (ArrayIndexOutOfBoundsException e) { System.out.println (“The element you requested is not available”); } But this may not be the best place to handle the error – at a higher level, we can write fewer catch blocks… maybe we move it up one level to causeTrouble( ).

How do I know the available exceptions? Some common ones: InputMismatchException NullPointerException ArrayIndexOutOfBoundsException ArithmeticException FileNotFoundException Consult reference for others – or you can create your own (later)

Checked Exceptions Can be caught by the compiler Ex: FileNotFoundException You must deal with them, or declare that your method ‘throws’ that exception (passes the buck).

How does the compiler know How do we distinguish checked exceptions?

How does the compiler know Sneaky… The constructor to certain objects will throw an Exception. If you make one of these objects, you need to catch it or throw it to your caller.

Unchecked Exceptions Things the compiler cannot know about. A variable is created, user sets it to zero, then divides by it. We can ‘catch’ them, or it is left to Java’s default exception handler, and you get the ugly stack trace message

I don’t want to catch it, I want to throw… public static void myMethod ( ) throws IOException, NumberFormatException { // if you call me, you need to catch those exceptions, or throw them again }

This is a pain This can be a lot of code, to catch every possible error in user input. You should do it anyway Commercial code is as much error checking as ‘real’ code.

Example import java.util.*; public class ExceptionExample { Scanner console = new Scanner(System.in); public static void main(String[] args) { try { System.out.println(“Enter 2 Numbers”); int quotient = console.nextInt() / console.nextInt(); } catch (Exception e) { if (e instanceof ArithmeticExcption) { System.out.println(“div by 0”); } else if (e instanceof InputMismatchException) { System.out.println(“Input Mismatch in Types” + e.toString() ); } } // end catch

throw statement throw new InputMismatchException(“my message”); This has the caller deal with it Note: we use another object with no name We pass a message string to the InputMismatchException constructor.

I want to do more than just display a message do { Scanner console = new Scanner(System.in); try { number = console.nextInt(); done = true; } catch (InputMismatchException e) { // give error message } }while (!done);

Just extend ‘Exception’ Then throw your new exception type and catch it. Making Your Own Exception Class