Java Programming Exceptions CSC 444 By Ralph B. Bisland, Jr.

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: when things go wrong. Various sources of error public static doSomething() { int i = 3.0; while(!done); { int i = false } ) Syntactic errors.
Lecture 23 Input and output with files –(Sections 2.13, 8.7, 8.8) Exceptions and exception handling –(Chapter 17)
CS102--Object Oriented Programming
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.
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.
Java Programming Exceptions. Java has a built in mechanism for error handling and trapping errors Usually this means dealing with abnormal events or code.
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.
1 Lecture 11 Interfaces and Exception Handling from Chapters 9 and 10.
Objectives Understanding what an exception is Understanding the heirarchy of exception classes Learn the types of exception and how to catch and handle.
EXCEPTIONS Def: An exception is a run-time error. Examples include: attempting to divide by zero, or manipulate invalid data.
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.
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.
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
06 Exception Handling. 2 Contents What is an Exception? Exception-handling in Java Types of Exceptions Exception Hierarchy try-catch()-finally Statement.
CIS 270—Application Development II Chapter 13—Exception Handling.
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.
Chapter 12 Handling Exceptions and Events. Chapter Objectives Learn what an exception is Become aware of the hierarchy of exception classes Learn about.
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 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:
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.
Agenda Introduction Errors and Exception Exception Hierarchy Classification of Exceptions Built in Exceptions Exception Handling in Java User defined.
ExceptionstMyn1 Exceptions You need to understand classes and inheritance before you can understand what an exception is and appreciate what happens when.
Java Exceptions a quick review….
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
Introduction to OO Program Design
CS102 – Exceptions David Davenport Latest: May 2015
Exceptions 10-Nov-18.
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.
Exceptions & exception handling
ATS Application Programming: Java Programming
Exceptions & exception handling
Chapter 12 Exception Handling
Abdulmotaleb El Saddik University of Ottawa
Exception Handling and Reading / Writing Files
Exception Handling.
CMSC 202 Exceptions 2nd Lecture.
CMSC 202 Exceptions 2nd Lecture.
Web Design & Development Lecture 7
Managing Errors and Exceptions
Lecture 11 Objectives Learn what an exception is.
CMSC 202 Exceptions 2nd Lecture.
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
Exception Handling Contents
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.
Exceptions 10-May-19.
Exceptions References: Jacquie Barker, Beginning Java Objects; Rick Mercer, Computing Fundamentals With Java; Wirfs-Brock et. al., Martin Fowler, OOPSLA.
Java Basics Exception Handling.
CMSC 202 Exceptions 2nd Lecture.
Exception Handling.
Java Programming: From Problem Analysis to Program Design, 4e
Presentation transcript:

Java Programming Exceptions CSC 444 By Ralph B. Bisland, Jr. Title Slid Java Programming Exceptions By Ralph B. Bisland, Jr. Drawing shadowed boxes with PowerPoint is easy. Simply use the Rectangle tool to draw the box and then choose Shadowed from the Draw menu. Be sure to delete this word processing box before using this template for your own presentation.

Exceptions A robust program deals gracefully with unexpected situations/conditions. Exceptions are unusual conditions that could arise when code is executing. The exception could make the continuation of the execution of the program impossible or undesirable. Examples of exceptions include: Divide by zero Arithmetic overflow index out of bounds

Exceptions (ctd) In Java terminology, exceptions are “thrown”. Exceptions may be system defined or user defined. Exceptions may be thrown by the system of by the programmer. Exception are “caught” with exception handlers - which is code that executes if the exception occurs. If no handler is written for the exception, the program terminates execution.

Exceptions (ctd) There are 20+ subclasses of Exceptions which are defined in the package java.lang.Throwable

Exception Hierarchy Object Throwable Error Exception RunTimeException

Exception Explanations Throwable: Superclass for all error handling. This class should not be used directly to describe a particular exception. Error: Indicates a severe problem from which recovery is difficult, if not impossible. Example: Running out of memory. It is probably best to report the error, then terminate execution of the program.

Exception Explanations (ctd) Exception: Super class for RunTimeExceptions. RunTimeException: Indicates a design or implementation problem. Example: IndexOutOfBoundsException. An attempt should probably be made to fix this type exception and continue execution of the program.

Partial Exception Hierarchy Object Throwable Exception RuntimeException ArithmeticException ArrayStoreException ClassCastException IllegalArgumentException NumberFormatException IllegalMonitorStateException IndexOutOfBoundsException ArrayIndexOutOfBoundsException StringIndexOurOfboundsException NegativeArraysizeException NullPointer Exception SecurityException

Checked Exceptions An exception to can be analyzed by the compiler. A checked exception must either be handled in the method or declared in the method signature via the throws clause. Example: IOException Designed to reduce the number of errors that could occur in program execution.

Unchecked Exceptions A subclass of RuntimeExceptions. These exceptions are not checked by the compiler because they would be difficult to check at compile time. Examples: ArithmeticException and NullPointerException.

Try-Catch To handle exceptions any block of code in which the exception could possible occur must be preceded by the “try” statement. If present the catch block(s) must lie directly below its try block. There may be multiple catch blocks, each catching a separate exception. Once the code in the exception handler is executed, control leaves the block.

Example try { some java code that could cause an exception to be thrown } catch (exception-type identifier) { code to handle the exception

A More Specific Example int x =; try { x = SimpleInput.readInt(); } Catch (NumberFormatException nfe) System.out.println (“You entered an illegal integer value”); Note: When this error occurs, the file pointer Does not move and the value currently stored In the variable ‘x” does not change.

Another Example class TestException {public static void main (String[] args) {String greetings [] = {“Hello there, I‘m Yogi Bear”, “Hi Boo-Boo”, “Welcome to Jellystone Park”}; for (int i = 0; i<= 3; i++) System.out.println (greetings[i]); }

Output orca% javac TestExc.java orca% java TestExc Hello there, I'm Yogi Bear Hi Boo-Boo Welcome to Jellystone Park java.lang.ArrayIndexOutOfBoundsException at TestExc.main(TestExc.java:8) orca%

Displaying Exceptions A method called toString can be used to convert the exception to text for display. Example: catch (Exception e) {system.out.println (e.toString);}

With Exceptions class TestException {public static void main (String[] args) {String greetings [] = {“Hello there, I‘m Yogi Bear”, “Hi Boo-Boo”, “Welcome to Jellystone Park”}; for (int i = 0; i<= 3; i++) try{System.out.println (greetings[i]);} catch (Exception e) {System.out.println(e.toString());} }

Output orca% javac TestExc1.java orca% java TestExc1 Hello there, I'm Yogi Bear Hi Boo-Boo Welcome to Jellystone Park java.lang.ArrayIndexOutOfBoundsException orca%

The exit() Method The exit() method is used to terminate execution of a Java program. An integer value must be “passed” to the exit method. This value is displayed as output so if there is more than one “exit” point, the programmer will know which exit caused termination of the program. Example: exit(0);

Unhandled Exceptions If the exception is not handled in the current block, control is transferred to the next outermost block when it may be handled. This process is called propogation of exceptions. If the exception eventually gets to the outermost block and is still not handled, execution of the program terminates,

Example Because there is no exception handler in the public static int processInput (……) { int x; . . . x = SimpleInput.readInt(); // Normal processing continues } Because there is no exception handler in the Block control is passed to the next outermost block. Problem: No value returned by the method.

Editing Input … boolean inputReadOK = false; While (!inputReadOK) try{ x = processInput (…); } catch (NumberFormatException e) {System.out.println (e); SimpleInput.readLine();// Move the file ptr System.out.println(“Input error try again”); inputReadOK = true; // normal processing continues here

A Complete Example import java.lang.*; import SimpleIO.*; class TestException {public static void main (String [] args) {int aNumber; boolean success = false; String inputString = “”; System.out.print (“Enter an integer: “); while (!success) { try { aNumber = SimpleInput.readInt(); success = true;} catch (NumberFormatException e) {inputString = SimpleInput.readString(); System.out.println (“The string: “ + inputString + “is not an integer” + “-- try again”);} } System.out.println (“You entered the integer value: “ + aNumber);

Catching Multiple Exceptions Multiple exceptions can be caught by including multiple catch blocks after the try block. Example: try{ } catch (exception1 e1) {code for this exception} catch (exception2 e2) {code for this exception}

The Finally Clause The finally clause associated with a try block ensures that a set of code will be executed whether the exception is thrown or not. The code in the finally block is usually referred to as ‘clean up” code. It is often used to do things like close files, write out final messages, etc.

Example Class FinallyTest {public static int aMethod (. . .) {. . . try { . . . } catch (IOException e) { . . .} . . . catch (EOFException e) { . . .} finally { . . . } } public static void main (String[] args { . . . }

Another Example class TestException {public static void main (String[] args) {String greetings [] = {“Hello there, I‘m Yogi Bear”, “Hi Boo-Boo”, “Welcome to Jellystone Park”}; for (int i = 0; i<= 3; i++) try{System.out.println (greetings[i]);} catch (Exception e) {System.out.println(e.toString());} finally {System.out.print (“Always displayed”);} } }

Output orca% javac TestExc2.java orca% java TestExc2 Hello there, I'm Yogi Bear Always displayed Hi Boo-Boo Welcome to Jellystone Park java.lang.ArrayIndexOutOfBoundsException orca%