Cop 3503 fall 2012 shayan javed lecture 11
Download
1 / 89

COP 3503 FALL 2012 Shayan Javed Lecture 11 - PowerPoint PPT Presentation


  • 109 Views
  • Uploaded on

COP 3503 FALL 2012 Shayan Javed Lecture 11. Programming Fundamentals using Java. Exception Handling. Errors. Syntax Errors Logic Errors Runtime Errors. Syntax Errors. Arise because language rules weren’t followed. Syntax Errors. Arise because language rules weren’t followed.

loader
I am the owner, or an agent authorized to act on behalf of the owner, of the copyrighted work described.
capcha
Download Presentation

PowerPoint Slideshow about ' COP 3503 FALL 2012 Shayan Javed Lecture 11' - deva


An Image/Link below is provided (as is) to download presentation

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.


- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript
Cop 3503 fall 2012 shayan javed lecture 11

COP 3503 FALL 2012ShayanJavedLecture 11

Programming Fundamentals using Java



Errors
Errors

  • Syntax Errors

  • Logic Errors

  • Runtime Errors


Syntax errors
Syntax Errors

  • Arise because language rules weren’t followed.


Syntax errors1
Syntax Errors

  • Arise because language rules weren’t followed.

  • Detected by the compiler

    • javac for Java

    • g++ for C++


Logic errors
Logic Errors

  • Program compiles and runs, but results are wrong.


Logic errors1
Logic Errors

  • Program compiles and runs, but results are wrong.

  • Detected and fixed through testing.


Logic errors2
Logic Errors

  • Program compiles and runs, but results are wrong.

  • Detected and fixed through testing.

  • Arise because logic coded by the programmer was incorrect.


Logic errors3
Logic Errors

  • Program compiles and runs, but results are wrong.

  • Detected and fixed through testing.

  • Arise because logic coded by the programmer was incorrect.

    • Example: wrote c = a - b instead of c = a + b


Runtime errors
Runtime Errors

  • Occur when program is running – environment detects it and can’t carry it out


Runtime errors1
Runtime Errors

  • Occur when program is running – environment detects it and can’t carry it out

  • Examples of Code Errors:

    • Divide by zero


Runtime errors2
Runtime Errors

  • Occur when program is running – environment detects it and can’t carry it out

  • Examples of Code Errors:

    • Divide by zero

    • Array out of bounds


Runtime errors3
Runtime Errors

  • Occur when program is running – environment detects it and can’t carry it out

  • Examples of Code Errors:

    • Divide by zero

    • Array out of bounds

    • Accessing a null pointer (reference)


Runtime errors4
Runtime Errors

  • Occur when program is running – environment detects it and can’t carry it out

  • Examples of Code Errors:

    • Divide by zero

    • Array out of bounds

    • Accessing a null pointer (reference)

    • Integer overflow


Runtime errors5
Runtime Errors

  • Occur when program is running – environment detects it and can’t carry it out

  • Examples of Code Errors:

    • Divide by zero

    • Array out of bounds

    • Accessing a null pointer (reference)

    • Integer overflow

  • Programs crash when such exceptions are not handled


Errors1
Errors

int[] numbers = { 1.5, 5, 7 };

System.out.prntln(numbers[numbers.length]);

Try to point out all the errors in this code


Errors2
Errors

int[] numbers = { 1.5, 5, 7 };

System.out.prntln(numbers[numbers.length]);

Syntax Error(s)


Errors3
Errors

int[] numbers = { 1.5, 5, 7 };

System.out.prntln(numbers[numbers.length]);

Syntax Error(s)


Errors4
Errors

int[] numbers = { 1.5, 5, 7 };

System.out.prntln(numbers[numbers.length]);

Syntax Error(s)

Runtime Error(s)


Exception
Exception

An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program’s instructions.


Exception handling in java
Exception Handling in Java

  • Mechanism for handling exceptions by detecting and responding to them in a systematic, uniform and reliable manner.


Exception handling in java1
Exception Handling in Java

  • Mechanism for handling exceptions by detecting and responding to them in a systematic, uniform and reliable manner.

  • Any exceptions not handled within the Java program are “caught” by the Java Runtime Environment (JRE)


Exception1
Exception

  • A method in Java throws Exceptions

    • “Something went wrong”


Exception2
Exception

  • A method in Java throws Exceptions

    • “Something went wrong”

  • Exceptions are Objects

    • Every Exception is a subclass of the Exception class




System errors1
System Errors

  • Thrown by the Java Virtual Machine (JVM)


System errors2
System Errors

  • Thrown by the Java Virtual Machine (JVM)

  • Represented by the Error class


System errors3
System Errors

  • Thrown by the Java Virtual Machine (JVM)

  • Represented by the Error class

  • Describes internal system errors


System errors4
System Errors

  • Thrown by the Java Virtual Machine (JVM)

  • Represented by the Error class

  • Describes internal system errors

  • Rarely occur – if they do you can’t do much other than terminating




Checked exceptions1
Checked Exceptions

Need to explicitly deal with

Checked Exceptions:

try and catch them, or throw them


Exception handling
Exception Handling

  • Keywords:

    • try some code, catch any Exceptions


Exception handling1
Exception Handling

  • Keywords:

    • try some code, catch any Exceptions

    • or throw an Exception


Exception handling2
Exception Handling

  • Keywords:

    • try some code, catch any Exceptions

    • or throw an Exception

    • finally execute some code


Exception handling3
Exception Handling

  • Java forces you to deal with checked Exceptions


Exception handling4
Exception Handling

  • Java forces you to deal with checked Exceptions

  • Two ways to deal with them:

void p1 () {

try {

riskyMethod();

}

catch (Exception ex) {

....

}

}

(a)


Exception handling5
Exception Handling

  • Java forces you to deal with checked Exceptions

  • Two ways to deal with them:

void p1 () {

try {

riskyMethod();

}

catch (Exception ex) {

....

}

}

(a)

void p1 () throws Exception {

riskyMethod();

}

(b)


Exception handling6
Exception Handling

  • Remember the clone() method?


Exception handling7
Exception Handling

  • Remember the clone() method?

  • Can be written in two ways:

Object clone() {

try {

return super.clone();

}

catch (CloneNotSupportedException ex) {

....

}

}

(a)


Exception handling8
Exception Handling

  • Remember the clone() method?

  • Can be written in two ways:

Object clone() {

try {

return super.clone();

}

catch (CloneNotSupportedException ex) {

....

}

}

(a)

Object clone() throws CloneNotSupportedException {

return super.clone();

}

(b)


Exception handling9
Exception Handling

  • In the first case, we are catching and handling the Exception


Exception handling10
Exception Handling

  • In the first case, we are catching and handling the Exception

  • In the second case we are throwing it – needs to be caught and handled by the calling method


Catching exceptions
Catching Exceptions

  • A try-catch statement:

    try {

    // Statement(s) which throw Exceptions

    } catch (Exception1exception1) {

    // Handles Exceptions of type Exception1

    } catch (Exception2exception2) {

    // Handles Exceptions of type Exception2

    } catch (Exceptionexception) {

    // Handles Exceptions of type Exception

    // ALL Exceptions

    }

    // Any code after the try-catch block


Catching exceptions1
Catching Exceptions

  • A try-catch statement:

    try {

    // Statement(s) which throw Exceptions

    } catch (CloneNotSupportedException exception1) {

    // Handles Exceptions of type CloneNotSupportedException

    } catch (NullPointerException exception2) {

    // Handles Exceptions of type NullPointerException

    } catch (Exceptionexception) {

    // Handles Exceptions of type Exception

    // ALL Exceptions

    }

    // Any code after the try-catch block


Catching exceptions2
Catching Exceptions

  • A try-catch statement:

    try {

    Circle clone = circle1.clone();

    } catch (CloneNotSupportedException exception1) {

    // Handles Exceptions of type CloneNotSupportedException

    } catch (NullPointerException exception2) {

    // Handles Exceptions of type NullPointerException

    } catch (Exceptionexception) {

    // Handles Exceptions of type Exception

    // ALL Exceptions

    }

    // Any code after the try-catch block


Catching exceptions3
Catching Exceptions

  • ThrownExceptions have to be eventually caught somewhere in your code


Exception information
Exception Information

  • So an Exception has been caught – what can we do with it?

    try {

    // Statements which throw Exceptions

    } catch (Exceptionexception) {

    // ALL Exceptions

    }


Exception information1
Exception Information

  • Some useful methods in the Throwable class:


Exception information2
Exception Information

  • Some useful methods in the Throwable class:

  • StringtoString():

    • Returns a short description of the Exception


Exception information3
Exception Information

  • Some useful methods in the Throwable class:

  • StringtoString():

    • Returns a short description of the Exception

  • StringgetMessage():

    • Returns a detailed description of the Exception


Exception information4
Exception Information

  • Some useful methods in the Throwable class:

  • StringtoString():

    • Returns a short description of the Exception

  • StringgetMessage():

    • Returns a detailed description of the Exception

  • voidprintStackTrace():

    • Prints the stacktrace information on the console


Exception information5
Exception Information

  • Some useful methods in the Throwable class:

  • voidprintStackTrace():

    • Prints the stacktrace information on the console

      Sample output:

      java.lang.NullPointerExceptionat MyClass.method2(MyClass.java:9) at MyClass.method1(MyClass.java:6) at MyClass.main(MyClass.java:3)


Exception information6
Exception Information

  • Example:

    java.io.PrintWriter output = null;

    try {

    output = newjava.io.PrintWriter(“text.txt”);

    output.println(“Welcome to Java”);

    output.close();

    }

    catch (java.io.IOException ex){

    System.out.println(ex.toString());

    ex.printStackTrace() ;

    }


Problems
Problems

  • Example:

    java.io.PrintWriter output = null;

    try {

    output = newjava.io.PrintWriter(“text.txt”);

    output.println(“Welcome to Java”);

    output.close();

    }

    catch (java.io.IOException ex){

    System.out.println(ex.toString());

    ex.printStackTrace() ;

    }

    Must execute output.close() even if Exception occurs


Solution
Solution

  • Use the finally clause – for code that must be executed “no matter what”


Solution1
Solution

  • Use the finally clause – for code that must be executed “no matter what”

    try {

    // Statement(s) which throw Exceptions

    } catch (Exception1exception1) {

    // Handles Exceptions of type Exception1

    } catch (Exceptionexception) {

    // Handles Exceptions of type Exception

    } finally {

    // code executed whether there is an Exception or not

    }


Solution2
Solution

  • Example:

    java.io.PrintWriter output = null;

    try {

    output = newjava.io.PrintWriter(“text.txt”);

    output.println(“Welcome to Java”);

    }

    catch (java.io.IOException ex){

    ex.printStackTrace() ;

    } finally {

    if (output != null)

    output.close();

    }


The finally block
The finally block

  • Executed when try block is exited in these ways:


The finally block1
The finally block

  • Executed when try block is exited in these ways:

    • After last statement of try block


The finally block2
The finally block

  • Executed when try block is exited in these ways:

    • After last statement of try block

    • After last statement of the catch block (if an Exception was caught)


The finally block3
The finally block

  • Executed when try block is exited in these ways:

    • After last statement of try block

    • After last statement of the catch block (if an Exception was caught)

    • When an Exception is thrown in try but NOTcaught


The finally block4
The finally block

  • Executed when try block is exited in these ways:

    • After last statement of try block

    • After last statement of the catch block (if an Exception was caught)

    • When an Exception is thrown in try but NOTcaught

      Executed even if there is a return statement prior to reaching the finally block


Throwing exceptions
Throwing Exceptions

  • If written code could encounter a runtime error:


Throwing exceptions1
Throwing Exceptions

  • If written code could encounter a runtime error:

  • It creates an Exception object and throws it


Throwing exceptions2
Throwing Exceptions

  • If written code could encounter a runtime error:

  • It creates an Exception object and throws it

  • and must also declare it in the method description


Throwing exceptions3
Throwing Exceptions

  • If written code could encounter a runtime error:

  • It creates an Exception object and throws it

  • and must also declare it in the method description

    • Only if the Exception is a checked Exception

    • Optional for unchecked


Throwing exceptions4
Throwing Exceptions

  • Example:

    publicvoidsetRadius(double newRadius)

    {

    if (newRadius >= 0)

    radius = newRadius;

    else

    throw new IllegalArgumentException(

    "Radius cannot be negative");

    }


Throwing exceptions5
Throwing Exceptions

  • Example:

    OPTIONAL

    publicvoidsetRadius(double newRadius) throwsIllegalArgumentException

    {

    if (newRadius >= 0)

    radius = newRadius;

    else

    throw new IllegalArgumentException(

    "Radius cannot be negative");

    }


Throwing exceptions6
Throwing Exceptions

try {

Circle c1 = newCircle(5);

c1.setRadius(-5);

}

catch (IllegalArgumentException ex) { System.out.println(ex);

}


Throwing exceptions7
Throwing Exceptions

try {

Circle c1 = newCircle(5);

c1.setRadius(-5);

}

catch (IllegalArgumentException ex) { System.out.println(ex);

}

Output:

Radius cannot be negative


Creating custom exceptions
Creating Custom Exceptions

  • Create custom Exception classes if predefined classes not sufficient


Creating custom exceptions1
Creating Custom Exceptions

  • Create custom Exception classes if predefined classes not sufficient

  • To create a custom class:

    • class should extend Exception


Creating custom exceptions2
Creating Custom Exceptions

  • Create custom Exception classes if predefined classes not sufficient

  • To create a custom class:

    • class should extend Exception

    • Good practice to add:

      • A default (empty) constructor

      • A constructor with one String parameter


Creating custom exceptions3
Creating Custom Exceptions

public class InvalidRadiusExceptionextends Exception {

private double radius;publicInvalidRadiusException() {

super(“Invalid radius!”);

}

publicInvalidRadiusException(double radius) {

super("Invalid radius!”);

this.radius = radius;

}

publicdoublegetRadius() {

return radius;

}

}


Creating custom exceptions4
Creating Custom Exceptions

  • Example:

    publicvoidsetRadius(double newRadius) throwsIllegalArgumentException

    {

    if (newRadius >= 0)

    radius = newRadius;

    else

    throw new IllegalArgumentException(

    "Radius cannot be negative");

    }


Creating custom exceptions5
Creating Custom Exceptions

  • Example:

    publicvoidsetRadius(double newRadius) throwsInvalidRadiusException

    {

    if (newRadius >= 0)

    radius = newRadius;

    else

    throw new InvalidRadiusException(radius);

    }


Creating custom exceptions6
Creating Custom Exceptions

try {

Circle c1 = newCircle(5);

c1.setRadius(-5);

}

catch (IllegalArgumentException ex) { System.out.println(ex);

}


Creating custom exceptions7
Creating Custom Exceptions

try {

Circle c1 = newCircle(5);

c1.setRadius(-5);

}

catch (InvalidRadiusException ex) { System.out.println(“Invalid Radius: “ + ex.getRadius());

}


Creating custom exceptions8
Creating Custom Exceptions

try {

Circle c1 = newCircle(5);

c1.setRadius(-5);

}

catch (InvalidRadiusException ex) { System.out.println(“Invalid Radius: “ + ex.getRadius());

}

Output:

Invalid Radius: -5.0


When to create custom exceptions
When to create Custom Exceptions

  • Use the exception classes in the API whenever possible.


When to create custom exceptions1
When to create Custom Exceptions

  • Use the exception classes in the API whenever possible.

  • Write your own custom exception class if you answer yes to one of the following:


When to create custom exceptions2
When to create Custom Exceptions

  • Use the exception classes in the API whenever possible.

  • Write your own custom exception class if you answer yes to one of the following:

    • Do you need an exception type that isn’t represented by Java?


When to create custom exceptions3
When to create Custom Exceptions

  • Use the exception classes in the API whenever possible.

  • Write your own custom exception class if you answer yes to one of the following:

    • Do you need an exception type that isn’t represented by Java?

    • Would it help users if they can differentiate your exceptions from those thrown by classes from other vendors?


When to create custom exceptions4
When to create Custom Exceptions

  • Use the exception classes in the API whenever possible.

  • Write your own custom exception class if you answer yes to one of the following:

    • Do you need an exception type that isn’t represented by Java?

    • Would it help users if they can differentiate your exceptions from those thrown by classes from other vendors?

    • Do you want to pass more than just a string to the exception handler?


When to use exceptions
When to use Exceptions

  • Use if the event is exception and truly an error


When to use exceptions1
When to use Exceptions

  • Use if the event is exception and truly an error

  • Do not use it to deal with simple, expected situations

  • Example:

try {

System.out.println(refVar.toString());

}

catch (NullPointerException ex) {

System.out.println("refVar is null");

}


When to use exceptions2
When to use Exceptions

  • Use if the event is exception and truly an error

  • Do not use it to deal with simple, expected situations

  • Example:

  • Replace with:

try {

System.out.println(refVar.toString());

}

catch (NullPointerException ex) {

System.out.println("refVar is null");

}

if (refVar != null)

System.out.println(refVar.toString());

else

System.out.println("refVar is null");


ad