260 likes | 273 Views
Learn about exception handling and logging in procedural languages like Java. Understand how to handle and log errors using try-catch blocks and how to create your own exception classes. Explore the concept of logging and how to implement it in your code.
E N D
Lecture 3 Exceptions, Singleton, Bridge & Logging
Error handling in procedural languages int foo() { if ( !doSomething1() ) return –1; … if ( !doSomething2() ) return –2; … }
Exceptions public interface Algorithm { public void run() throws ExecutionException, IllegalDataException; }
Example int[] iArray = randomSortedIntArray(); IAlgorithm alg = new BinarySearch( iArray, 29 ); try { alg.run(); } catch ( IllegalDataException e1 ) { System.err.println( "Illegal Data Exception while running Binary Search: " + e.getMessage() ); e.printStackTrace(); } catch ( ExecutionException e ) { System.err.println( "Execution Exception while running Binary Search " + e.getMessage() ); e.printStackTrace(); }
How the catch block works if ( thrown exception instance of IllegalDataException ) { … } else if ( thrown exception instanceof ExecutionException ) { … }
printStackTrace method java.io.FileNotFoundException: fred.txt at java.io.FileInputStream.<init>(FileInputStream.java) at java.io.FileInputStream.<init>(FileInputStream.java) at ExTest.readMyFile(ExTest.java:19) at ExTest.main(ExTest.java:7)
Swallowing exceptions is is a major NO-NO! try { anObject.method( arg1 );} catch ( Exception e ) {}
Exceptions allow for extra info… public class ParserException extends Exception { public ParserException( File f, int iLine ) { this.f = f; this.iLine = iLine; } public final File getFile() { return f; } public final int getLine() { return iLine; } private File f; private int iLine; }
Creating your own exception classes public class ApplicationException extends Exception {} public class ApplicationOpenFailedException extends ApplicationException {}
Throwing multiple exceptions public interface IApplication { public void open() throws ApplicationOpenFailedException, IOException; public void close() throws ApplicationCloseFailedException, IOException; }
finally public class AlwaysDoThatWithStreams { public static void main( String[] args ) { FileWriter fw = null; try { fw = new FileWriter( "args.txt" ); for ( int i = 0; i < args.length; i++ ) { os.println( "ARG[" + i + "] = [" + args[ i ] + "]" ); } } catch ( IOException e ) { System.out.println( "Error while writing args: " + e.getMessage() ); } finally { if ( fw != null ) fw.close(); } } }
public static int parseInt(String s, int radix) throws NumberFormatException
Logging 01/01/2002 9:45:03 [EntityReader] ERROR: class StrangeEntity not found 01/01/2002 9:45:05 [EntityReader] DEBUG: created instance of BasicEntity Log.error( this, "class StrangeEntity not found" ); Log.debug( this, "created instance of BasicEntity" );
Singleton public class Singleton { public static Singleton getInstance() { return instance; } private Singleton() {} // create instance private static Singleton instance = new Singleton(); public static void main( String[] args ) { Singleton handle1 = Singleton.getInstance(); Singleton handle2 = Singleton.getInstance(); System.out.println( "Handle1 [" + handle1 + "]" ); System.out.println( "Handle2 [" + handle2 + "]" ); } } Handle1 [Singleton@1c9f7e] Handle2 [Singleton@1c9f7e]
Log class public final class Log { public static void debug( String msg ); public static void debug( Object this, String msg ); public static void error( String msg ); public static void error( Object this, String msg ); public static void warning( String msg ); public static void warning( Object this, String msg ); public static void setOptionsOn( int options ); public static void setOptionsOff( int options ); public static void setPrinter( ILogPrinter lp ); public static ILogPrinter getPrinter(); public static void registerClass( Class c ); public static void unregisterClass( Class c ); }
Log as utility class Log.getInstance().error( "Something is wrong" ); Log.error( "Something is wrong" );
Basic Log methods public final class Log { public static void error( String msg ); public static void error( Object o, String msg ); public static void debug( String msg ); public static void debug( Object o, String msg ); }
Passing the object whichreports the message public static void error( Object o, String msg ) { Log( "ERROR: " + o.getClass().getName() + ":" + msg ); }
Factoring out the implementation public class ILogImpl { public void print( String sMessage ); }
Factoring out the implementation public class Log { … public static void setLogImpl( ILogImpl lm ) { logImpl = lm; } … private void print( String s ) { logImpl.print( s ); } private static ILogImpl logImpl; }
StdOutLogImpl public final class StdOutLogImpl implements ILogImpl { public StdOutLogImpl () {} public void print( String s ) { System.out.println( s ); } }
Complete Log class public class Log { /** * @param Object o - the object, which signals the error * @param String sMsg - the error message * @param Throwable - the exception which occurred */ public static void error( Object o, String sMsg, Throwable e ); public static void error( String sMsg, Throwable e ); public static void error( Object o, String sMsg ); public static void error( String sMsg ); public static void debug( Object o, String sMsg ); public static void debug( String sMsg ); public static void warning( Object o, String sMsg ); public static void warning( String sMsg ); /** * @param Boolean bDebug - indicates if the debugging messages * should be printed or not */ public static void setDebug( boolean bDebug ); public static boolean getDebug(); /** * @param ILogImpl logImpl - the settable delegate which * actually does the printing of the messages. * It is specific to the medium where the messages go. */ public static void setLogImpl( ILogImpl logImpl ); private Log(); }
Assignment Please read Arnold & Gosling Java Programming language Chapters on Exception and Garbage collection Chapters 16 and 25 from Agile Software Development Book Assignment 1 Define & implement Log, ILogImpl, StdOutLogImpl, FileLogImpl, MultiLogImpl