Writing your own Exceptions. How to extend Exception

Similar documents
Exceptions. Examples of code which shows the syntax and all that

Exceptions. What exceptional things might our programs run in to?

Exceptions Handling Errors using Exceptions

Exceptions. Errors and Exceptions. Dealing with exceptions. What to do about errors and exceptions

Errors and Exceptions

BBM 102 Introduction to Programming II Spring Exceptions

Data Structures. 02 Exception Handling

COMP 213. Advanced Object-oriented Programming. Lecture 17. Exceptions

National University. Faculty of Computer Since and Technology Object Oriented Programming

Java Programming Unit 7. Error Handling. Excep8ons.

Exceptions and Libraries

COMP200 EXCEPTIONS. OOP using Java, based on slides by Shayan Javed

Exceptions - Example. Exceptions - Example

16-Dec-10. Consider the following method:

Exceptions vs. Errors Exceptions vs. RuntimeExceptions try...catch...finally throw and throws

Inheritance. SOTE notebook. November 06, n Unidirectional association. Inheritance ("extends") Use relationship

More on Objects in JAVA TM

CSCI 261 Computer Science II

Checked and Unchecked Exceptions in Java

CS115. Chapter 17 Exception Handling. Prof. Joe X. Zhou Department of Computer Science. To know what is exception and what is exception handling

BBM 102 Introduction to Programming II Spring 2017

Day 8. COMP1006/1406 Summer M. Jason Hinek Carleton University

PIC 20A Exceptions. Ernest Ryu UCLA Mathematics. Last edited: November 27, 2017

Full file at Chapter 2 - Inheritance and Exception Handling

A problem?... Exceptions. A problem?... A problem?... Suggested Reading: Bruce Eckel, Thinking in Java (Fourth Edition) Error Handling with Exceptions

CSC207H: Software Design. Exceptions. CSC207 Winter 2018

Exceptions, try - catch - finally, throws keyword. JAVA Standard Edition

Exceptions. References. Exceptions. Exceptional Conditions. CSE 413, Autumn 2005 Programming Languages

Exception-Handling Overview

Exceptions. CSE 142, Summer 2002 Computer Programming 1.

Exceptions. Readings and References. Exceptions. Exceptional Conditions. Reading. CSE 142, Summer 2002 Computer Programming 1.

What is it? CMSC 433 Programming Language Technologies and Paradigms Spring Approach 1. Disadvantage of Approach 1

Exceptions. Produced by. Introduction to the Java Programming Language. Eamonn de Leastar

Object oriented programming. Instructor: Masoud Asghari Web page: Ch: 7

Exceptions. Produced by. Algorithms. Eamonn de Leastar Department of Computing, Maths & Physics Waterford Institute of Technology

A Third Look At Java. Chapter Seventeen Modern Programming Languages, 2nd ed. 1

Fundamentals of Object Oriented Programming

CS11 Java. Fall Lecture 4

Lecture 14 Summary 3/9/2009. By the end of this lecture, you will be able to differentiate between errors, exceptions, and runtime exceptions.

Exception Handling CSCI 201 Principles of Software Development

Sri Vidya College of Engineering & Technology Question Bank

More on Exception Handling

Abstract Classes, Exceptions

More on Exception Handling

Exception Handling. Sometimes when the computer tries to execute a statement something goes wrong:

Exceptions. CSC207 Winter 2017

Exception Handling. Run-time Errors. Methods Failure. Sometimes when the computer tries to execute a statement something goes wrong:

Chapter 3 Java Exception

엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University COPYRIGHTS 2017 EOM, HYEONSANG ALL RIGHTS RESERVED

Introduction. Exceptions: An OO Way for Handling Errors. Common Runtime Errors. Error Handling. Without Error Handling Example 1

CS 61B Discussion 5: Inheritance II Fall 2014

Title. Java Just in Time. John Latham. February 8, February 8, 2018 Java Just in Time - John Latham Page 1(0/0)

13: Error Handling with Exceptions. The basic philosophy of Java is that "badly formed code will not be run."

EXCEPTIONS. Objectives. The try and catch Statements. Define exceptions. Use try, catch and finally statements. Describe exception categories

2018/2/5 话费券企业客户接入文档 语雀

6.005 Elements of Software Construction

Introduction to Computer Science II CS S-22 Exceptions

G51PGP Programming Paradigms. Lecture 009 Concurrency, exceptions

Lab 2: File Input and Output

EXCEPTIONS. Java Programming

To Think About. MyClass.mogrify(new int[] { 1, 2, 4, 6 }));

Self-test Java Programming

Administration. Exceptions. Leftovers. Agenda. When Things Go Wrong. Handling Errors. CS 99 Summer 2000 Michael Clarkson Lecture 11

CS61B Lecture #12. Today: Various odds and ends in support of abstraction.

CS1092: Tutorial Sheet: No 3 Exceptions and Files. Tutor s Guide

6.Introducing Classes 9. Exceptions

Assertions and Exceptions Lecture 11 Fall 2005

Exceptions & Miscellaneous Lecture 17

Exception Examples. All examples written by Edith Hemaspaandra and modified by Jessica Bayliss

class objects instances Fields Constructors Methods static

About This Lecture. Outline. Handling Unusual Situations. Reacting to errors. Exceptions

ITI Introduction to Computing II

Exceptions and I/O: sections Introductory Programming. Errors in programs. Exceptions

Introductory Programming Exceptions and I/O: sections

Rules and syntax for inheritance. The boring stuff

Exception handling & logging Best Practices. Angelin

Recreation. MyClass.mogrify(new int[] { 1, 2, 4, 6 }));

Classes, interfaces, & documentation. Review of basic building blocks

JAC444 - Lecture 4. Segment 1 - Exception. Jordan Anastasiade Java Programming Language Course

ITI Introduction to Computing II

Chair of Software Engineering. Java and C# in Depth. Prof. Dr. Bertrand Meyer. Exercise Session 7. Nadia Polikarpova

Chapter 9. Exception Handling. Copyright 2016 Pearson Inc. All rights reserved.

09/08/2017 CS2530 INTERMEDIATE COMPUTING 9/8/2017 FALL 2017 MICHAEL J. HOLMES UNIVERSITY OF NORTHERN IOWA TODAY S TOPIC: Exceptions and enumerations.

Lecture 4: Exceptions. I/O

Defensive Programming. Ric Glassey

CmpSci 187: Programming with Data Structures Spring 2015

Software Construction

Exception Handling in Java

Programming II (CS300)

Programming Languages and Techniques (CIS120)

Lists. Chapter 12. Copyright 2012 by Pearson Education, Inc. All rights reserved

Topic 6: Exceptions. Exceptions are a Java mechanism for dealing with errors & unusual situations

Exception Handling BASIC EXCEPTION HANDLING OBJECTIVES PREREQUISITES

For more details on SUN Certifications, visit

Chapter 15. Exception Handling. Chapter Goals. Error Handling. Error Handling. Throwing Exceptions. Throwing Exceptions

EXCEPTION-HANDLING INTRIVIEW QUESTIONS

Object Oriented Design. Object-Oriented Design. Inheritance & Polymorphism. Class Hierarchy. Goals Robustness Adaptability Flexible code reuse

Review. Errors. Ø Users may enter data in the wrong form Ø Files may not exist Ø Program code has bugs!*

COE318 Lecture Notes Week 10 (Nov 7, 2011)

What can go wrong in a Java program while running?

Transcription:

Writing your own Exceptions How to extend Exception

When would you write your own exception class? When to write your own custom exception is a matter for discussion in your project design team. There could be some reasons for doing so which we ll discuss briefly. This lecture is more about the syntax, than about such design decisions. You might want to keep exceptions as a part of your package, so that users of your class, doesn t have to bother about exceptions from totally unrelated packages. For instance, you might want to hide some exceptions because they make clients of your code dependent on other packages.

Example of hiding an exception If you have a class for fetching a list of objects, this might be done using a number of technologies, which may change over the evolution of your application. You might start with fetching them from the filesystem, then move on to fetching them from a database and end up fetching them over the internet using some service. Clients of your code should probably not have to know or worry about how your class fetches the objects. Having to deal with exceptions from other APIs may create a dependency - SQLExceptions, IOExceptions etc are examples.

A possible solution If we have a class for fetching objects, say Member objects from some storage to some application for Member management, clients of this class will have to import the package where the class exists. But if the class uses a database for fetching, it might throw some SQLException from the fetch() method. This would mean that clients of this class would have to import also java.sql.sqlexception for instance. This is a tight coupling between clients and an external API, which isn t what we want. We could then create our own Exception and wrap any SQLExceptions.

System layout client code fetchall() What to throw? Storage class for fetching Members some JDBC stuff SQLException Database We don t want client code to import SQLException, because that would tie them to a database solution which might change...

System layout with custom exception client code fetchall() Storage class for fetching Members some JDBC stuff SQLException Database MemberStorageException We use our own MemberStorageException class which wraps the SQLException. Client code now only has to depend on classes in our package, and we can replace the database with anything else, but keep our exception!

Extending RuntimeException or Exception? Which one to extend is not an easy question to answer. But you should know that extending Exception creates a checked exception, so the same discussion as in previous lectures can be applied - do we want the compiler to enforce exception handling on our clients? Extend Exception! A different way of looking at this could be to ask a different question: Can we expect the client code to handle the exception and fix the problem? Extend Exception and use checked exceptions. If they cannot fix the problem, we might as well use RuntimeException.

Extending Exception To extend Exception, simply write a class with a descriptive name and declare that the class extends Exception. Next, provide at least the following two constructors: public YourException(String message){ super(message); // allow for the getmessage() to work public YourException(String message, Throwable cause){ super(message, cause); // allow for wrapping an exception

Wrapping an exception Wrapping an exception was what we did when we threw an exception of some type, but created it with a message and another exception like so: catch(ioexception e){ throw new SomeOtherException("I/O problem", e); The client code can, if it needs it, investigate the cause, using the method getcause() which will return the wrapped exception if it exists, or null if there is no wrapped exception.

Code example (focusing on syntax!) public static void main(string[] args){ try{ dostuff(); catch(mycheckedexception e){ // catch a custom Exception type System.err.println("A MyCheckedException occurred: " + e.getmessage()); if(e.getcause()!=null){ // check for wrapped exception System.err.println("The cause was: " + e.getcause()); static void dostuff()throws MyCheckedException{ // throw a custom exceptio which wraps a NullPointerException throw new MyCheckedException("Something went wrong", new NullPointerException("Bad monkey"));

MyCheckedException public class MyCheckedException extends Exception{ // Provide two constructors which call the super class public MyCheckedException(String message){ super(message); public MyCheckedException(String message, Throwable cause){ super(message, cause);

Recap Creating our own exceptions exposes less dependencies to client code Extend Exception if you want to have a checked exception Extend RuntimeException if the clients can t fix the problem anyway Just use extends and provide at least two constructors (String message) (String message, Throwable cause) Call the superclass constructors respectively