Exceptions Syntax, semantics, and pragmatics Exceptions1.

Slides:



Advertisements
Similar presentations
Exceptions CSE301 University of Sunderland Harry Erwin, PhD.
Advertisements

Error Handling in.NET Exceptions. Error Handling Old way (Win32 API and COM): MyFunction() { error_1 = doSomething(); if (error_1) display error else.
Lecture 23 Input and output with files –(Sections 2.13, 8.7, 8.8) Exceptions and exception handling –(Chapter 17)
CS102--Object Oriented Programming
Errors and Exceptions The objectives of this chapter are: To understand the exception handling mechanism defined in Java To explain the difference between.
CSE 332: C++ exceptions Overview of C++ Exceptions Normal program control flow is halted –At the point where an exception is thrown The program call stack.
Chapter 8Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 8 l Basic Exception Handling »the mechanics of exceptions l.
Exceptions1 Syntax, semantics, and pragmatics. Exceptions2 Syntax, semantics, pragmatics Syntax –How it looks, i.e. how we have to program to satisfy.
Exceptions Any number of exceptional circumstances may arise during program execution that cause trouble import java.io.*; class IOExample { public static.
EXCEPTIONS. What’s an exception?? Change the flow of control when something important happens ideally - we catch errors at compile time doesn’t happen.
Exceptions1 Syntax, semantics, and pragmatics. Exceptions2 Syntax, semantics, pragmatics Syntax –How it looks, i.e. how we have to program to satisfy.
Lecture 28 More on Exceptions COMP1681 / SE15 Introduction to Programming.
Exceptions and Exception Handling (2) Carl Alphonce CSE116.
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.
Slides prepared by Rose Williams, Binghamton University Chapter 9 Exception Handling.
1 From Yesterday private = accessible only to the class that declares it public = accessible to any class at all protected = accessible to the class 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. 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.
Exception Handling An Exception is an indication of a problem that occurs during a program’s execution. Exception handling enables the programmer to create.
Exceptions. 2 Objectives Introduce C# exception handling –library exception types –custom exceptions Describe keywords used for exception handling –try.
Slides prepared by Rose Williams, Binghamton University Chapter 9 More Exception Handling.
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.
Chapter 13 Exception Handling F Claiming Exceptions F Throwing Exceptions F Catching Exceptions F Rethrowing Exceptions  The finally Clause F Cautions.
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.
Java Programming Exceptions Handling. Topics: Learn about exceptions Try code and catch Exceptions Use the Exception getMessage() method Throw and catch.
1 CSC241: Object Oriented Programming Lecture No 27.
COMPUTER PROGRAMMING 2 Exceptions. What are Exceptions? Unexpected events that happen when the code is executing (during runtime). Exceptions are types.
Exceptions1 Syntax, semantics, and pragmatics. Exception create If (some error){ throw new SomeException(”some message”); } Exceptions2.
Contract based programming Using pre- and post-conditions, and object invariants Contract based programming1.
VB.Net - Exceptions Copyright © Martin Schray
Introduction to Exception Handling and Defensive Programming.
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.
Exception Handling Programmers must deal with errors and exceptional situations: User input errors Device errors Empty disk space, no memory Component.
Computer Programming with JAVA Chapter 8. Exception Handling Basic Exception Handling the mechanics of exceptions Defining and Using Exceptions some "simple"
CSE 332: C++ Statements C++ Statements In C++ statements are basic units of execution –Each ends with ; (can use expressions to compute values) –Statements.
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.
ICS3U_FileIO.ppt File Input/Output (I/O)‏ ICS3U_FileIO.ppt File I/O Declare a file object File myFile = new File("billy.txt"); a file object whose name.
Copyright © Curt Hill Error Handling in Java Throwing and catching exceptions.
Chapter 8-Exception Handling/ Robust Programming.
1 Exceptions. 2 Syntax Errors, Runtime Errors, and Logic Errors syntax errors, runtime errors, and logic errors You learned that there are three categories.
(c) University of Washington10-1 CSC 143 Java Errors and Exceptions Reading: Ch. 15.
Lecture10 Exception Handling Jaeki Song. Introduction Categories of errors –Compilation error The rules of language have not been followed –Runtime error.
Exception Handling How to handle the runtime errors.
Effective Java, Chapter 9: Exceptions Items Last modified Fall 2012 Paul Ammann.
C# Exceptions 1 CNS 3260 C#.NET Software Development.
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.
Winter 2006CISC121 - Prof. McLeod1 Last Time Reviewed class structure: –attributes –methods –(inner classes) Looked at the effects of the modifiers: –public.
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.
OOP Tirgul 7. What We’ll Be Seeing Today  Packages  Exceptions  Ex4 2.
CSE 332: C++ Exceptions Motivation for C++ Exceptions Void Number:: operator/= (const double denom) { if (denom == 0.0) { // what to do here? } m_value.
Syntax, semantics, and pragmatics
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.
CNS 3260 C# .NET Software Development
Exceptions & Error Handling
Effective Java, 3rd Edition Chapter 10: Exceptions
Programming in C# Lesson 5. Exceptions..
Java Exceptions Dan Fleck CS211.
Exceptions 25-Apr-19.
Exceptions 22-Apr-19.
CSC 143 Java Errors and Exceptions.
Effective Java, Chapter 9: Exceptions
Exceptions 10-May-19.
CMSC 202 Exceptions 2nd Lecture.
Exception Handling.
Presentation transcript:

Exceptions Syntax, semantics, and pragmatics Exceptions1

Syntax, semantics, and pragmatics Syntax How it looks, i.e. how we have to program to satisfy the compiler. Semantics What it means / how it works Pragmatics How to use it in the proper way. Exceptions2

Introduction Exceptions are thrown from methods when something exceptional (un-expected) happens. Whether something is exceptional or not is a design issue. Is it exceptional to search a list for a non-existing element? Probably not Don’t throw an exception, return null Is it exceptional to open a non-existing file? Probably yes Throws FileNotFoundException Exceptions3

Exception related syntax try { … } catch (SomeException ex) { … } In the try block you call methods that might throw exceptions In the catch block you handle the exceptions thrown in the try block (if any) try { … } catch (SomeException ex) { … } finally The finally block is executed after the try block (and the catch block) no matter if there was an exception, or not. Usually used to close resources like files, database connections, network connections, etc. try { … } finally Sometimes you omit the catch block If you only want proper close of resources Exceptions4

The using statement With the using statements resources will automatically be opened and closed. No need for finally { …. resource.close() … } Example: TryingUsing Syntax Using (declare + open the resource) { … use the resource … } // resource is automatically closed. Works on all resources (classes) implementing the interface System.Idisposable Has a single method void dispose() Source Exceptions5

Throwing an exception If something un-expected happens your method can throw an exception. You really throw an exception object, i.e. an object of a class that extends the class Exception Syntax: throw new SomeException(…) Semantics: You leave the method. More syntax: No exception declarations in method signatures Public int divide(int a, int b) The return type is declared, in this case int. However, the type of exceptions that might be thrown is not declared In this case DiviceByZeroException Exceptions6

Exceptions and the call stack Every program has a call stack. The main() method is the bottom of the call stack Every method call pushes a new element on the call stack Method return pops an element of the call stack Throw an exception pops an element of the call stack The popping continues until the exception is caught Or if it is never caught the main() is popped from the stack, and the program terminates Exceptions7

Some exception properties Message property Text message explaining what is wrong StackTrace property Shows all the methods that was popped of the call stack InnerException property Used for exception chaining (more on that later on) Exceptions8

Sequence of catch blocks A single try statement may have several catch blocks. Each catch block handling a separate exception Catch more specific exceptions before general exceptions Example: catch the specific FileNotFoundException before the general IOException Otherwise your program does not compile And it does not make sense! Example: TryUsing -> ReadFirstLine -> Main Exceptions9

Different kinds of exception handling Ignore (an empty catch block) Generally a bad idea Does it make sense to continue program execution after ignoring the exception? If you really want the catch block to be empty, you should leave a comment for the human reader /* this catch block is intentionally left empty */ Handle Catch and do something. If you can’t do anything better than Console.print(…), don’t do it! Does it make sense to continue program execution after the catch block? Partly handle Catch the exception Do something (could be Console.print(…)) Throw the exception (or another exception) Exceptions10

Some commonly used exception classes NullReferenceException You tried to call a method on a object reference which is null Student st = null; … St.someMethod(); // NullReferenceException New throw a NullReferenceException ArgumentException You have a problem with a parameter (argument) to a method ArgumentNullException Parameter with value null is not allowed ArgumentOutOfRangeException Parameter value is out of range IndexOutOfRangeException You have a problem with our array index OutOfMemoryException You have created to many object StackOverflowException To many method calls. Normally because a method is calling itself to many times. More detailed exception More detailed information about the problem Easier /better handling of the problem Exceptions11

Making your own exception types It is really easy to make another exception type, just extend the class Exception directly or in-directly Class MyException : Exception { … } Normally you your exception class will have a few constructors. Example: TryingUsing The model layer should include a homemade exception Example: A hotel reservation system should have a HotelReservationException Technical exceptions should stay at the technical layers Catch (TechException ex) { throw new ModelException(ex); } Exceptions12

Exception chaining + exception translation If you want to catch a technical (low level) exception and instead throw a model exception (high level) you have two possibilities Exception translation Catch (TechException ex) { throw new ModelException(ex.Message); } The ModelException holds the same message as the TechException Exception chaining Catch (TechException ex) { throw new ModelException(ex); } The ModelException holds a reference to the TechException The property InnerExceptions holds the reference to the inner exception Example: LayeredLibrary Exceptions13

References and further reading MSDN Handling and Throwing Exceptions Exceptions14