81
JAVA: Chapter 6 Exception & Multithreading 1

JAVA: Chapter 6 Exception & Multithreading

  • Upload
    erek

  • View
    66

  • Download
    1

Embed Size (px)

DESCRIPTION

JAVA: Chapter 6 Exception & Multithreading. Learning Outcome. At the end of this slide, student able to understand the concept of multithreading and exception handling. . Exception-Handling Overview . What do you think if 4 divided by 0?. Exception-Handling Overview . - PowerPoint PPT Presentation

Citation preview

Chapter 1 Introduction to Java

JAVA: Chapter 6 Exception & Multithreading1Learning OutcomeAt the end of this slide, student able to understand the concept of multithreading and exception handling. 23Exception-Handling Overview What do you think if 4 divided by 0?

3Exception-Handling Overview It is possible JAVA can calculate this equation?

4Exception-Handling Overview JAVA cannot calculate that equation, the output will be failed!!

5Exception Overviewpackage quotient;import java.util.Scanner;public class Quotient { public static void main(String[] args) { Scanner input = new Scanner(System.in); // Prompt the user to enter two integers System.out.print("Enter two integers: "); int number1 = input.nextInt(); int number2 = input.nextInt(); try { int result = number1 / number2; System.out.println(number1 + " / " + number2 + " is " + result); } catch (ArithmeticException ex) { System.out.println("Exception: an integer cannot be divided by zero"); } }}

6import java.util.Scanner;

public class QuotientWithIf { public static void main(String[] args) { Scanner input = new Scanner(System.in); // Prompt the user to enter two integers System.out.print("Enter two integers: "); int number1 = input.nextInt(); int number2 = input.nextInt(); if (number2 != 0) System.out.println(number1 + " / " + number2 + " is " + (number1 / number2)); else System.out.println("an integer cannot be divided by zero"); }}

Exception Overviewimport java.util.*;

public class InputMismatchExceptionDemo { public static void main(String[] args) { Scanner input = new Scanner(System.in); boolean continueInput = true;

do { try { System.out.print("Enter an integer: "); int number = input.nextInt(); // Display the result System.out.println( "The number entered is " + number); continueInput = false; } catch (InputMismatchException ex) { System.out.println("Try again. (" + "Incorrect input: an integer is required)"); input.nextLine(); // discard input } } while (continueInput); }}

7Example of Exception8ExceptionDescriptionArithmeticExceptionArithmetic error, such as divide-by-zero.ArrayIndexOutOfBoundsExceptionArray index is out-of-bounds.ArrayStoreExceptionAssignment to an array element of an incompatible type.ClassCastExceptionInvalid cast.IllegalArgumentExceptionIllegal argument used to invoke a method.IllegalMonitorStateExceptionIllegal monitor operation, such as waiting on an unlocked thread.IllegalStateExceptionEnvironment or application is in incorrect state.IllegalThreadStateExceptionRequested operation not compatible with current thread state.IndexOutOfBoundsExceptionSome type of index is out-of-bounds.NegativeArraySizeExceptionArray created with a negative size.NullPointerExceptionInvalid use of a null reference.NumberFormatExceptionInvalid conversion of a string to a numeric format.SecurityExceptionAttempt to violate security.StringIndexOutOfBoundsAttempt to index outside the bounds of a string.UnsupportedOperationExceptionAn unsupported operation was encountered.Other ExceptionAWTExceptionAclNotFoundExceptionActivationExceptionAlreadyBoundExceptionApplicationExceptionArithmeticExceptionArrayIndexOutOfBoundsExceptionAssertionExceptionBackingStoreExceptionBadAttributeValueExpExceptionBadBinaryOpValueExpExceptionBadLocationExceptionBadStringOperationExceptionBatchUpdateExceptionBrokenBarrierExceptionCertificateExceptionChangedCharSetExceptionCharConversionExceptionCharacterCodingExceptionClassCastExceptionClassNotFoundExceptionCloneNotSupportedExceptionClosedChannelExceptionConcurrentModificationException DataFormatException9DatatypeConfigurationExceptionDestroyFailedExceptionEOFExceptionExceptionExecutionExceptionExpandVetoExceptionFileLockInterruptionExceptionFileNotFoundExceptionFishFaceExceptionFontFormatExceptionGSSExceptionGeneralSecurityExceptionIIOExceptionIOExceptionIllegalAccessExceptionIllegalArgumentExceptionIllegalClassFormatExceptionIllegalStateExceptionIndexOutOfBoundsException InputMismatchExceptionInstantiationExceptionInterruptedExceptionInterruptedIOExceptionIntrospectionExceptionInvalidApplicationExceptionInvalidMidiDataExceptionInvalidPreferencesFormatExceptionInvalidTargetObjectTypeExceptionInvocationTargetExceptionJAXBExceptionJMExceptionKeySelectorExceptionLastOwnerExceptionLineUnavailableExceptionMalformedURLExceptionMarshalExceptionMidiUnavailableExceptionMimeTypeParseExceptionNamingExceptionNegativeArraySizeExceptionNoSuchElementExceptionNoSuchFieldExceptionNoSuchMethodExceptionNoninvertibleTransformExceptionNotBoundExceptionNotOwnerExceptionNullPointerExceptionNumberFormatExceptionObjectStreamExceptionParseExceptionParserConfigurationExceptionPrintExceptionPrinterExceptionPrivilegedActionExceptionPropertyVetoException

10ProtocolExceptionRefreshFailedExceptionRemarshalExceptionRemoteExceptionRuntimeExceptionSAXExceptionSOAPExceptionSQLExceptionSQLWarningSSLExceptionScriptExceptionServerNotActiveExceptionSocketExceptionSyncFailedExceptionTimeoutExceptionTooManyListenersExceptionTransformExceptionTransformerExceptionURIReferenceExceptionURISyntaxExceptionUTFDataFormatExceptionUnknownHostExceptionUnknownServiceExceptionUnmodifiableClassExceptionUnsupportedAudioFileExceptionUnsupportedCallbackExceptionUnsupportedEncodingExceptionUnsupportedFlavorExceptionUnsupportedLookAndFeelExceptionUnsupportedOperationExceptionUserExceptionXAExceptionXMLParseExceptionXMLSignatureExceptionXMLStreamExceptionXPathExceptionZipExceptionFriendly Advice about ExceptionActually, it is very difficult to remember all exception especially to junior programmer. However, the programmer can use online recourses such as: http://docs.oracle.com/javase/7/docs/api/ as assistance. 1112System Errors

System errors are thrown by JVM and represented in the Error class. The Error class describes internal system errors. Such errors rarely occur. If one does, there is little you can do beyond notifying the user and trying to terminate the program gracefully. 13Exceptions

Exception describes errors caused by your program and external circumstances. These errors can be caught and handled by your program. 14Runtime Exceptions

RuntimeException is caused by programming errors, such as bad casting, accessing an out-of-bounds array, and numeric errors.15Throwing Exceptions Example /** Set a new radius */ public void setRadius(double newRadius) throws IllegalArgumentException { if (newRadius >= 0) radius = newRadius; else throw new IllegalArgumentException( "Radius cannot be negative"); }16Catching Exceptionstry { statements; // Statements that may throw exceptions}catch (Exception1 exVar1) { handler for exception1;}catch (Exception2 exVar2) { handler for exception2;}...catch (ExceptionN exVar3) { handler for exceptionN;} 17Catching Exceptions

18Trace a Program Executionanimationtry { statements;}catch(TheException ex) { handling ex; }finally { finalStatements; }

Next statement;Suppose no exceptions in the statements19Trace a Program Executionanimationtry { statements;}catch(TheException ex) { handling ex; }finally { finalStatements; }

Next statement;The final block is always executed20Trace a Program Executionanimationtry { statements;}catch(TheException ex) { handling ex; }finally { finalStatements; }

Next statement;Next statement in the method is executed21Trace a Program Executionanimationtry { statement1; statement2; statement3;}catch(Exception1 ex) { handling ex; }finally { finalStatements; }

Next statement;Suppose an exception of type Exception1 is thrown in statement222Trace a Program Executionanimationtry { statement1; statement2; statement3;}catch(Exception1 ex) { handling ex; }finally { finalStatements; }

Next statement;The exception is handled.23Trace a Program Executionanimationtry { statement1; statement2; statement3;}catch(Exception1 ex) { handling ex; }finally { finalStatements; }

Next statement;The final block is always executed.24Trace a Program Executionanimationtry { statement1; statement2; statement3;}catch(Exception1 ex) { handling ex; }finally { finalStatements; }

Next statement;The next statement in the method is now executed.25Trace a Program Executionanimationtry { statement1; statement2; statement3;}catch(Exception1 ex) { handling ex; }catch(Exception2 ex) { handling ex; throw ex;}finally { finalStatements; }

Next statement;statement2 throws an exception of type Exception2.26Trace a Program Executionanimationtry { statement1; statement2; statement3;}catch(Exception1 ex) { handling ex; }catch(Exception2 ex) { handling ex; throw ex;}finally { finalStatements; }

Next statement;Handling exception27Trace a Program Executionanimationtry { statement1; statement2; statement3;}catch(Exception1 ex) { handling ex; }catch(Exception2 ex) { handling ex; throw ex;}finally { finalStatements; }

Next statement;Execute the final block28Trace a Program Executionanimationtry { statement1; statement2; statement3;}catch(Exception1 ex) { handling ex; }catch(Exception2 ex) { handling ex; throw ex;}finally { finalStatements; }

Next statement;Rethrow the exception and control is transferred to the caller29Multithreading30Overview of multithreadingVSWhich one is the most lightness?WHY??

31Overview of multithreadingBecause of in Mozilla Firefox, there are too many process inside, compared to IE (internet explorer).

32Overview of multithreadingWhat will happened if the software have too many process inside?33Overview of multithreadingThe software become slow *Slow like snails34Overview of multithreadingThread == process;Multithread == multi process;

Thats why we need to learn about multithreading, so then, we know what the causes of the SLOW SOFTWARE and how to prevent from develop a slow software.35Creating Tasks and Threads

35package taskthreaddemo;public class TaskThreadDemo { public static void main(String[] args) { // Create tasks Runnable printA = new PrintChar('a', 100); Runnable printB = new PrintChar('b', 100); Runnable print100 = new PrintNum(100);

// Create threads Thread thread1 = new Thread(printA); Thread thread2 = new Thread(printB); Thread thread3 = new Thread(print100);

// Start threads thread1.start(); thread2.start(); thread3.start(); }}

// The task for printing a specified character in specified timesclass PrintChar implements Runnable { private char charToPrint; // The character to print private int times; // The times to repeat

/** Construct a task with specified character and number of * times to print the character */ public PrintChar(char c, int t) { charToPrint = c; times = t; }

@Override /** Override the run() method to tell the system * what the task to perform */ public void run() { for (int i = 0; i < times; i++) { System.out.print(charToPrint); } }}

// The task class for printing number from 1 to n for a given nclass PrintNum implements Runnable { private int lastNum;

/** Construct a task for printing 1, 2, ... i */ public PrintNum(int n) { lastNum = n; }

@Override /** Tell the thread how to run */ public void run() { for (int i = 1; i