Exceptions handling Try, catch blocks Throwing exceptions.

Slides:



Advertisements
Similar presentations
Topics Introduction Types of Errors Exceptions Exception Handling
Advertisements

Exceptions Chapter Throwing and Catching Exceptions When a program runs into a problem that it cannot handle, it throws an exception. Exceptions.
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 23 Input and output with files –(Sections 2.13, 8.7, 8.8) Exceptions and exception handling –(Chapter 17)
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.
MIT-AITI Lecture 14: Exceptions Handling Errors with Exceptions Kenya 2005.
Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.
COP 2800 Lake Sumter State College Mark Wilson, Instructor.
1 / 89 COP 3503 FALL 2012 SHAYAN JAVED LECTURE 11 Programming Fundamentals using Java 1.
Exceptions. 2 Objectives Introduce C# exception handling –library exception types –custom exceptions Describe keywords used for exception handling –try.
Java Exception Handling ● Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions: – Examples:
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.
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.
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 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.
CS 2511 Fall  Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions:  Examples: Out.
Spring 2008 Mark Fontenot CSE 1341 Principles of Computer Science I Note Set 10.
Practice Session 9 Exchanger CyclicBarrier Exceptions.
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. Exception  Abnormal event occurring during program execution  Examples Manipulate nonexistent files FileReader in = new FileReader("mumbers.txt“);
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.
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.
Exceptions in OO Programming Introduction Errors Exceptions in Java Handling exceptions The Try-Catch-Finally mechanism Example code Exception propagation.
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.
Introduction to Exceptions in Java CS201, SW Development Methods.
1 Handling Errors and Exceptions Chapter 6. 2 Objectives You will be able to: 1. Use the try, catch, and finally statements to handle exceptions. 2. Raise.
Lecture 5: Exception Handling and Text File I/O Michael Hsu CSULA.
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.
CSE 1201 Object Oriented Programming
Lec.11 (Chapter 11) Exception Jiang (Jen) ZHENG July 13 th, 2005.
Exceptions handling Try, catch blocks Throwing exceptions.
Java Exceptions a quick review….
Exceptions In this lecture:
Tirgul 13 Exceptions 1.
MIT AITI 2003 Lecture14 Exceptions
Introduction to Exceptions in Java
Creating and Modifying Text part 2
Testing and Exceptions
Advanced Programming Behnam Hatami Fall 2017.
ATS Application Programming: Java Programming
Chapter 12 Exception Handling and Text IO
Exceptions Problems in a Java program may cause exceptions or errors representing unusual or invalid processing. An exception is an object that defines.
Abdulmotaleb El Saddik University of Ottawa
Unit 6 Working with files. Unit 6 Working with files.
Web Design & Development Lecture 7
Exception Handling in Java
Interrupts Hardware Software.
Lecture 11 Objectives Learn what an exception is.
Java Exceptions Dan Fleck CS211.
Exceptions handling Try, catch blocks Throwing exceptions.
Chapter 12 Exception Handling and Text IO Part 1
Exceptions.
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.
Exceptions.
Exception Handling.
Java Programming: From Problem Analysis to Program Design, 4e
Exceptions and Exception Handling
Presentation transcript:

Exceptions handling Try, catch blocks Throwing exceptions. Exceptions in Java Exceptions handling Try, catch blocks Throwing exceptions.

What is an Exception? An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions.

Example (file not found) void readFile() { Charset charset = Charset.forName("US-ASCII"); BufferedReader reader = Files.newBufferedReader(“input.txt”, charset)) String line = null; while ((line = reader.readLine()) != null) System.out.println(line); } Should work fine, however, what if the file input.txt is not there one day when you are running this program?

Example (file not found) void readFile() { Charset charset = Charset.forName("US-ASCII"); try { BufferedReader reader = Files.newBufferedReader(file, charset)) String line = null; while ((line = reader.readLine()) != null) System.out.println(line); } catch (IOException x) {System.err.format("IOException: %s%n", x);}

3 kinds of exceptions 1) Checked exceptions. User can anticipate Ex) file not found. 2) Error exceptions. Error that are external to the applications like hardware exceptions. Ex) cell phone overheats. 3) Runtime exception. Logic error in code and improper used of API, etc. Ex) divide by zero

Flow of control when an exception Should the exception be ignored? Show the Operating System always terminate the Process? Can the exception be handled (go to plan B) and then program continue? Should the programmer have the option to do some clean up prior to the Operating System terminating the program? Should all exceptions be handled the same way. Should the programmer anticipate an exception, and then be able to handle it as they choose.

Exception stack. Exception Handler code for various Exceptions are available from the Operating System. A process has a stack of addresses of where the code is located. When an exception occurs, an object of the type of the exception is created and “thrown” to the stack (top to bottom) looking for the first type match…that code is then run

Creating you own exception objects Consider the following : Your Mathematical exception library might be organized like this. class ArithmeticException { void toString( ) { return (instanceof() + “{: “ + getLocalizedMessage()); } } ; class UnderflowException extends ArithmeticException { } ; class ZeroDivideException extends ArithmeticException { } ; class OverflowException extends ArithmeticException void toString( ) { return “no problem here…” ;}

Catching exceptions Comments: the Dividezero will never run because Dividezero is a Mather try { // some math code goes here } catch (OverflowException) { // code to handle an over flow catch(ArithmeticException) // Handle any math error that is not an overflow catch(Dividezero) // Handle any Divide by zero

Throwable Class in Java class Throwable extends Object implements Serializable { } class Exception extends Throwable

Stack Trace A stack trace is a list of the method calls that the application was in the middle of when an Exception was thrown. Exception in thread "main" java.lang.IllegalStateException: A book has a null property at com.example.myproject.Author.getBookIds(Author.java:38) at com.example.myproject.Bootstrap.main(Bootstrap.java:14) Caused by: java.lang.NullPointerException at com.example.myproject.Book.getId(Book.java:22) at com.example.myproject.Author.getBookIds(Author.java:35) ... 1 more

Throwing Exceptions (intentionally) static int divide(int x, int y) { if(y==0) { throw new ZeroDivisionException; } return x/y; } … try { divide(12, 0); catch (DivideByZero) System.out.print(“divide by zero error”); System.out.print(“Moving right along”);

throw e vs throw new e ... Catch (MathError ME) { // handle it then throws exception of whatever type came in throw ME; } vs. if (ME instanceOf ZeroDivisionException) throw new ZeroDivisionException; // throws exception of type MathError

throws public void func() void gunc() throws IOException { } void hunc() { try { func(); gunc(); } catch (IOException e) { … }

finally The finally block always executes when the try block exits. This ensures that the finally block is executed even if an unexpected exception occurs. But finally is useful for more than just exception handling — it allows the programmer to avoid having cleanup code accidentally bypassed by a return, continue, or break. Putting cleanup code in a finally block is always a good practice, even when no exceptions are anticipated.

read a list<Integer> from a file List<Integer> list = new ArrayList<Integer>(); File file = new File("file.txt"); BufferedReader reader = null; try { reader = new BufferedReader(new FileReader(file)); String text = null; while ((text = reader.readLine()) != null) { list.add(Integer.parseInt(text)); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { if (reader != null) { reader.close(); } } catch (IOException e) { }

Exceptions are Thread Safe Java exception handling is thread safe. Throwing on one thread (including re-throws) has no impact on any throw/catch in progress on another thread.