Java for C Programmers Second Night Overview First Night Basics Classes and Objects Second Night Enumerations Exceptions Input Output Templates vs Generics STL vs JavaSE API Second Night Agenda Enumerations Exceptions Input Output enumeration declaration usage exception hierarchy checked vs unchecked exceptions throwing catching exceptions scanner class console I O file I O Discussion Lab exercises Break Templates vs Generics STL vs JavaSE API Discussion Lab exercises Enumerated Values in C One way to define a set of enumerated values constants in C is as follows const const const const int int int int CLUBS 0 DIAMONDS 1 HEARTS 2 SPADES 3 Example usage good invocations DrawSuit CLUBS DrawSuit HEARTS void DrawSuit int s draws the suit in a GUI Enumerated Values in Java Here s the Java port of that C code public class Suit public static public static public static public static final final final final int int int int CLUBS 0 DIAMONDS 1 HEARTS 2 SPADES 3 Everything looks good right good invocations drawCard Suit CLUBS drawCard Suit DIAMONDS static void drawCard int s draws the suit in a GUI Enumerated Values in Java Well sort of as long as the user behaves themselves bad invocations drawCard Suit HEARTS 5 drawCard 516 static void drawCard int s draws the suit in a GUI Using something unbounded like an int or a String can be problematic need to restrict the available choices Enumerations in Java Thankfully there s a better way to enumerate a set of values staring in Java 5 there is an enumerated type Similar to enum construct in C C Enums are declared similarly to classes public enum Suit CLUBS DIAMONDS HEARTS SPADES Enumerations in Java Now each constant is strongly typed When something is expecting a suit we specify a Suit enum type Invalid usage is now caught at compile time good invocations drawCard Suit CLUBS drawCard Suit DIAMONDS compiler errors drawCard Suit HEARTS 5 drawCard 516 static void drawCard Suit s draws the symbol for the suit in a GUI Enumerations in Java Additionally we can switch on enums draws the symbol for the suit in a GUI static void drawCard Suit s switch s case CLUBS case SPADES switch color to black then draw break default switch color to red then draw break Enumerations in Java We can also give enums in Java additional members and methods public enum Planet VENUS 4 8685e24 6051 8e3 EARTH 5 9736e24 6378 1e3 MARS 0 64185e24 3397e3 public static final double G 6 67300E 11 final double mass final double radius Planet double mass double radius this mass mass this radius radius double surfaceGravity return G mass radius radius double surfaceWeight double otherMass return otherMass surfaceGravity Enumerations Example usage similar to a class acceptable usage drawPlanet Planet EARTH System out println Surface gravity on earth System out println Planet EARTH surfaceGravity But we get compiler errors if we try to construct more compiler errors Planet EARTH new Planet 1 0 1 0 Planet p new Planet 1 0 1 0 Exceptions in C C allows us to throw anything as an exception Here is a modified factorial function which throws the number back if it is less than 0 int factorial int n check for exceptional case if n 0 throw n computation for normal case int result 1 for int i n i 0 i result i return result Exceptions in C Example catching of that exception in C int main int argc char argv int num 4 try cout factorial num factorial num endl catch int i cerr i is not valid endl return 0 Exceptions in C We can also throw more complex types for example here is a custom exception class which stores an error message class Exception private string m message public Exception string message m message message string GetMessage return this m message Exceptions in C Factorial function modified to throw custom exception type int factorial int n check for exceptional case if n 0 throw Exception number must be positive computation for normal case int result 1 for int i n i 0 i result i return result Exceptions Example catching of that exception in C int main int argc char argv int num 4 try cout factorial num factorial num endl catch Exception e cerr e GetMessage endl return 0 Exceptions in Java In Java we cannot throw primitives or most objects Anything that is thrown must be a Throwable or a valid subclass Though typically we throw Exceptions or subclasses Object Throwable Error Error Error Exception Error Error RuntimeException Error Error Exceptions in Java Here s a Java port of that second example We re using the built in Exception class static int factorial int n check for exceptional case if n 0 throw new Exception number must be positive computation for normal case int result 1 for int i n i 0 i result i return result Exceptions in Java Here is the invoking function in Java with the try catch block added public static void main String args int num 4 try System out println factorial num factorial num catch Exception e System err println e getMessage Exceptions in Java But if we try to compile this we get the following error javac exe Factorial java Factorial java 19 unreported exception java lang Exception must be caught or declared to be thrown throw new Exception number must be positive 1 error Why Java Exception Hierarchy Java breaks up Exceptions into 2 categories Unchecked you do not need to explicitly handle these exceptions Checked you must handle these in your code failure to do so is a compiler error Object Throwable Error Error Error Exception Error Error Checked Unchecked RuntimeException Error Error Handling Checked Exceptions We have one of 2 options Handle the exception locally wrap code in a try catch block Propagate the exception by adding a throws declaration to the method signature Exceptions in Java The modified factorial function modified to declare an thrown exception static int factorial int n throws Exception check for exceptional case if n 0 throw new Exception number must be positive computation for normal case int result 1 for int i n i 0 i result i return result Exceptions in Java Other notes about exceptions in Java e printStackTrace will print out the full stack trace as to where an exception originated e getMessage will give you a detailed message string as to why the exception occurred Try catch blocks may also have a finally section with code in it Always executed even if a return or throw is encountered Console I O in C Simple C class that reads writes to the console include iostream using namespace std int main int n string s cout What do you want to
View Full Document