Docsity

Exception Handling in Java, Lecture notes of Object Oriented Programming

Partial preview of the text

Download Exception Handling in Java and more Lecture notes Object Oriented Programming in PDF only on Docsity!

CMSC132-

Exceptions

Send me your pet pictures!

Thank you Kyra for the photos of Pickle

(RIP)!

Agenda

● Announcements

● Polymorphism Wrap Up

● Exceptions

Upcasting and Downcasting

● We have already seen that we can assign a derived class reference anywhere that a base class is expected (e.g., person1 = student1)

○ Upcasting: Casting a reference to a base class (casting up the inheritance tree). This is

done automatically and is always safe

○ Downcasting: Casting a reference to a derived class. The casting will only work if the type

of actual object associated with the variable is lower in the inheritance tree (e.g., you are

casting a Student to a Person and not the other way around). Before you cast, you must

verify (using instanceof) that the actual type of the object allows for the downcasting. If

you donʼt check you risk generating a ClassCastException at run-time

● Example: UpCastingDownCasting.java ● Example: SafeDownCasting.java

○ As elements are removed from the list, they must be downcast from Person to Student,

but this can only be done if the object really is a Student

Abstract Modifier

● Description ○ Represents generic concept ○ Just a placeholder ○ Leave lower-level details to subclass ● Applied to ○ Methods ○ Classes ● Example abstract class Foo { // abstract class abstract void bar( ); // abstract method public void doSomething(){ System.out.println(“Hello”); } } Example: withAbstractClass

Multiple Inheritance

● Motivation: There are many situations where a simple class hierarchy is not adequate to describe a classʼ structure ○ Example: Suppose that we have our class hierarchy of university people and we also develop a class hierarchy of athletic people:

● StudentAthlete: Suppose we want to create an object that inherits all the elements of a Student (admission year, GPA) as well as all the elements of an Athlete (sport, amateur-status)

Common Uses of Interfaces

● Interfaces are flexible things and can be used for many purposes in Java: ○ A work-around for Javaʼs lack of multiple inheritance. (We have just seen this.) ○ Specifying minimal functional requirements for classes (This is its principal purpose.) ○ For defining groups of related symbolic constants. (This is a somewhat unexpected use, but is not uncommon.) ○ To “tag” a class as belonging to a group. In this case there will be no methods associated with the interface. ○ Example: You would like to create an ArrayList with all things on Earth

Disabling Overriding with final

● We can disable overriding by declaring a method to be “final” ● Sometimes you do not want to allow method overriding

○ Correctness : Your method only makes sense when applied to the base class. Redefining

it for a derived class might break things

○ Efficiency : Late binding is less efficient than early binding. You know that no subclass

will redefine your method. You can force early binding by disabling overriding

● Example: The class Object defines the following method:

○ getClass( ): returns a description of a class. You can test whether two objects x and y are

of the same class with.

if ( x.getClass( ) == y.getClass( ) ) …

○ This is a very useful function. But clearly, we do not want arbitrary classes screwing

around with it. The getClass() method is a final

● Example: getArea() final method in withAbstractClass.Circle

Disabling Overriding with final

● final: Has different meanings, depending on context: ● Define symbolic constants: ○ public static final int MAX_BUFFER_SIZE = 1000; ● Indicate that a method cannot be overridden by derived classes public class Parent { public final void someMethod( ) { … } } public class Child extends Parent { public void someMethod( ) { … } } ● A class can be defined as final what will not allow the class to be extended. For example, public final class Circle extends Shape will not allow us to define a SuperCircle class that extends Circle ● A final class cannot be extended ○ String class is an example of a final class ■ Too important for others to change the behavior associated with String methods

Debugging in Java

Types of errors

● “Compile time” caught by Eclipse / Java compiler

○ Syntax errors

○ Disobeys the rules of the language; violates languageʼs grammar

○ Type errors: misuse of variables

● “Run time” appear during program execution

○ Semantic errors

○ Obeys the rules of the language but does not express them meaning you intended;

○ Division by 0

○ Crash or hang or wrong outputs (because of mistakes in programming)

● Logic

○ Project runs and compiles just fine, unexpected result

What to do with errors?

● Alternatives ○ Ignore error ○ Print error message and terminate ○ Have the method handle the error in the code where the problem lies as best as you can ○ Have the method pass it off to someone else to handle ■ Usually an error code is returned to whoever called the method ○ Modern language approach: Exception!

Dealing with Exceptions

● What to do when this kind of event occurs? ○ Ignore the problem ○ Print error message ○ Request data ○ Exit method returning error code caller must check ○ Exit program ● Exiting method returning error code has disadvantages ○ Calling method may forget to check code ○ Agreement on error codes ○ Error handling code mixed with normal code ● Preferred approach: Exception Handling (e.g., Javaʼs exception mechanism)

Exceptions

● Do nothing ○ Usually your program will be terminated by the JVM ○ Stack trace is printed showing where exception was generated

■ Red and blue in Eclipse window

○ Example: MilesPerGallon.java ● Do something about it ○ In some applications aborting the program is not an option ○ Email processor, web/database server ○ We can “handle” the exception by “catching the exception” and defining code to be executed

■ Use try { } to enclose code that can potentially throw an exception

■ Use catch(EXCEPTIONTYPE e) { } to “catch” the exception and define the code to execute when

the exception occurs

○ Example: MilesPerGallon2.java

What to do when an Exception occurs?

● When an exception occurs control “jumps” to the catch clause and code after the point where the exception occurred is not executed ● If the exception is not thrown the code of the catch clause is ignored ● Exception Object ○ When an exception is thrown, a new exception object is created, which encodes information about the nature of the exception ● Every Exception object supports the following methods: ○ Exception(String message) ■ Constructor taking an explanation as an argument ○ String getMessage() Returns a message describing the exception ○ void printStackTrace() Prints the contents of the Java call stack at the time of the exception

What to do when an Exception Occurs?

● There are different types of exceptions, depending on the error ArithmeticException divide by zero NullPointerException attempt to access an object with a null reference IndexOutOfBoundsException array or string index out of range ArrayStoreException attempting to store an object of type X in an array of type Y EmptyStackException attempt to pop an empty Stack (java.util). IOException attempt to perform an illegal input/output operation (java.io) NumberFormatException attempt to convert an invalid string into a number (e.g., when calling Integer.parseInt( ) ) ... Exception : The most generic type of exception ● All of these are Objects in Javaʼs class library (most in java.lang)