Cursus Tomcat Stack tracing - PowerPoint PPT Presentation

About This Presentation
Title:

Cursus Tomcat Stack tracing

Description:

Exception Handling try, catch and finally Exception information Generated Stack Trace NullPointerExceptions ClassCastExceptions NumberFormat Exceptions Multiple catch clauses User Defined Exceptions Chained Exceptions Reading Stack Traces – PowerPoint PPT presentation

Number of Views:2
Updated: 10 March 2023
Slides: 23
Provided by: Username withheld or not provided
Tags:

less

Transcript and Presenter's Notes

Title: Cursus Tomcat Stack tracing


1
  • Error Conditions
  • Exceptions in Java
  • Exception Handling
  • Syntax Exception Handling
  • Finally Clause
  • Exception information
  • Stack Traces
  • Generated Stack Trace
  • Predefined Exceptions
  • NullPointerExceptions
  • ClassCastExceptions
  • NumberFormat Exceptions
  • Multiple catch clauses
  • User Defined Exceptions
  • Chained Exceptions
  • Reading Stack Traces
  • Assertions
  • Tomcat Stack Tracing

2
Error Conditions
  • Software programs may produce errors
  • Wrong input
  • File not found
  • Array out of bounds
  • Memory exhausted
  • Harddisk failure
  • Programming error
  • Important is what happens after an error occurs
  • How and where is the error handled
  • Can the program continue or should it die
    gracefully
  • Typical problems with testing integer error
    return values
  • Program may need the return value functionally
  • Lot of testing code for rare conditions
  • Functional and error handling code mixed

3
Exceptions in Java
  • Exceptions are error conditions arising in code
    at run time
  • Benefits of exceptions versus using error codes
  • Separate error handling code and normal code
  • Enable propagation of errors up the call stack
  • Enable grouping of error types
  • When abnormal condition in method arises
  • Exception object created
  • Exception is thrown
  • At some point exception must be caught
  • Exception object contains information about
  • Type of exception
  • State of program when error occurred

4
Exception Handling
  • Handling of exceptions provides two benefits
  • Allows fixing of the error by printing a stack
    trace where the error occurred
  • Prevents program from terminating
  • Done by guarding code with try block
  • Code inside block is monitored
  • Follow try block with
  • catch clause specifying type of exception you
    wish to catch
  • Or finally clause to cleanup resources
  • Once the specified exception is thrown
  • Program control transfers to catch clause
  • Execution does not return from a catch to the try
    block
  • Once catch has executed
  • Program control continues with next line after
    try/catch
  • catch clause can shows stack trace with
    printStackTrace()
  • Stack trace can also be logged

5
Syntax Exception Handling
  • public class HelloStackTracesHandled
  • static Logger log Logger.getLogger(HelloStackTr
    aces.class.getName())
  • public static void main(String args)
  • BasicConfigurator.configure()
  • try
  • int i 10
  • int j 0
  • //int j 1
  • int result 0
  • result i / j
  • System.out.println("The result is "
    result)
  • catch (Exception e)
  • e.printStackTrace()
  • log.error("Exception occurred", e)
  • System.out.println(After catch
    statement)

Demo ArithmeticException
6
Finally Clause
  • Follows try or optionally try/catch combination
  • Code under finally is always executed
  • Useful for cleanup operations like freeing
    resources
  • If no exception is thrown
  • Control passes to the finally block
  • If exception is thrown, and no matching catch
    exists
  • Control passes to the finally block
  • If an exception is thrown and caught
  • Control passes to finally block after the catch
    block has executed
  • Even if catch block throws an exception or
    executes a return statement

7
Exception Information
  • Retrieve exception information by calling methods
  • Exception class does not define methods
  • All methods are derived from Throwable
  • getMessage
  • Returns a string description of the exception
  • toString
  • Returns string with exception class type,
    followed by the description
  • printStackTrace
  • Displays call stack of the program at the time
    the exception was thrown
  • catch (Exception e) // Handle the
    generic exception
  • System.out.println("Object type "
    e.toString())
  • e.printStackTrace()

8
Stack Traces
  • User friendly snapshot of call stack of thread in
    JVM
  • Depending on complexity of application
  • Stack trace can range from fifty lines to
    thousands of lines of diagnostics
  • Stack trace is generated by
  • Static method dumpStack of the Thread class
  • printStackTrace method of the Throwable class
  • JVM in case of an internal error
  • Stack traces help in localizing bugs and program
    flow
  • Higher chance of getting bugs fixed, because
    developers know where to fix bug
  • Most important concept of correctly understanding
    stack trace 
  • Lists execution path in reverse chronological
    order from recent to earliest operation
  • Analyzing stack traces is like analyzing compiler
    errors correctly
  • Order matters start with the first error
  • In case of chained exceptions
  • First look at the underlying caused by exception

9
Generated Stack Trace
10
Predefined Exceptions
Exception
RuntimeException
ArithmeticException
ClassCastException
ClassNotFoundException

CloneNotSupportedException
NullPointerException
IllegalAccessException
NumberFormatException
InstantiationException
IndexOutOfBoundsException
InterruptedException
NoSuchFieldException
NoSuchMethodException
11
ArrayIndexOutOfBoundsException
  • Thrown when location in array is accessed that
    does not exist
  • Requested array index is negative
  • Requested array index greater than or equal to
    the size of the array
  • Default error message printed when this error
    occurs
  • Includes the line number and the invalid index
    itself
  • Makes such failures relatively easy to debug
  • public class HelloStackTracesHandled
  • static Logger log Logger.getLogger(HelloStackTr
    aces.class.getName())
  • public static void main(String args)
  • BasicConfigurator.configure()
  • try
  • System.out.println("First commandline
    argument is " args0)
  • catch (Exception e)
  • log.error("Exception occurred", e)

Demo ArrayIndexOutOfBoundsException
12
NullPointer Exceptions
  • Most common exception that occurs during runtime
  • Cause is that some reference variable is null,
    does not point to a real object
  • Null pointer exceptions can be debugged as
    follows
  • Identify the line where it occurred and find out
    which object is null
  • public class HelloStackTracesHandled
  • static Logger log Logger.getLogger(HelloStackTr
    aces.class.getName())
  • ArrayList al
  • public static void main(String args)
  • BasicConfigurator.configure()
  • HelloStackTracesHandled ho new
    HelloStackTracesHandled()
  • try
  • ho.al.add(new Date())
  • Object obj ho.al.get(0)
  • System.out.println(obj)
  • catch (Exception e)
  • log.error("Exception occurred", e)

Demo NullPointerException
13
ClassCastExceptions
  • Thrown when you try to cast Object of one type to
    another 
  • Casting is allowed as long as the casting happens
    between compatible data types
  • ClassCastException occurs when the types are
    incompatible
  • Default error message printed when this error
    occurs
  • Says which type cannot be cast to which other
    type
  • public class HelloStackTracesHandled
  • static Logger log Logger.getLogger(HelloStackTr
    aces.class.getName())
  • ArrayList al new ArrayList()
  • public static void main(String args)
  • BasicConfigurator.configure()
  • HelloStackTracesHandled ho new
    HelloStackTracesHandled()
  • try
  • ho.al.add(new Date())
  • String s (String) ho.al.get(0)
  • System.out.println(s)
  • catch (Exception e)
  • log.error("Exception occurred", e)

Demo ClassCastException
14
NumberFormatException
  • May occur when String is converted to an int,
    float or double
  • String may not have the correct format
  • Typically occurs when user enters numeric data in
    an input field
  • NumberFormatException may be prevented by input
    validation
  • public class HelloStackTracesHandled
  • static Logger log Logger.getLogger(HelloStackTr
    aces.class.getName())
  • public static void main(String args)
  • BasicConfigurator.configure()
  • try
  • System.out.println("Please enter an integer
    value ")
  • Scanner c new Scanner(System.in)
  • String s c.next()
  • int i Integer.parseInt(s)
  • System.out.println("The integer you entered
    was " i)
  • catch (Exception e)
  • log.error("Exception occurred", e)

Demo NumberFormatException
15
Throwing User Defined Exception
  • Define ZipCodeException by extending Exception
  • class ZipCodeException extends Exception
  • public ZipCodeException(int BadZip)
  • super( BadZip " is not valid.
  • Zip must be a number between 1
    and 99999 inclusive.")
  • Create and throw a ZipCodeException
  • public void setZipCode(int zip) throws
    ZipCodeException
  • if (( zip gt 0) (zip lt 100000))
  • zipcodezip
  • else
  • throw new ZipCodeException(zip)

16
Catch User Defined Exception
  • Calling a method throwing ZipCodeException
  • public static void main(String args)
  • BasicConfigurator.configure()
  • HelloStackTracesHandled ud new
    HelloStackTracesHandled()
  • try
  • ud.setZipCode(-1)
  • catch (Exception e)
  • log.error("Exception occurred", e)
  • public void setZipCode(int zip) throws
    ZipCodeException
  • if (( zip gt 0) (zip lt 100000))
  • zipcodezip
  • else
  • throw new ZipCodeException(zip)

Demo UserDefinedException
17
Multiple Catch Clauses
  • try block may also be followed by multiple catch
    clauses
  • Same piece of code may generate several types of
    exceptions
  • Each catch clause handles a different type of
    exception
  • Exception thrown
  • catch clauses are inspected in order
  • First one whose type matches the exception type
    is executed
  • Other catch clauses are bypassed thereafter
  • catch handler for a superclass exception type
  • Will also handle exceptions of all subclasses
  • try
  • int x
  • //This next statement can produce multiple
    exceptions
  • x1/(x0)
  • catch (ArithmeticException e)
    //error handler
  • catch (ArrayIndexOutofBoundsException e)
    //another handler

Demo MultipleThreads
18
Chained Exceptions
  • class Class01
  • void meth01() throws ExceptionOne
  • try meth02()
  • catch (ExceptionTwo e)
  • System.out.println("Msg is\n"
    e.getMessage())
  • System.out.println("Cause is\n"
    e.getCause())
  • throw new ExceptionOne("Msg from meth01", e)
  • void meth02() throws ExceptionTwo
  • try meth03()
  • catch (RuntimeException e)
  • System.out.println("Cause is\n"
    e.getCause())
  • throw new ExceptionTwo("Msg from meth02",
    e)
  • void meth03()
  • try int x 3 / 0
  • catch (ArithmeticException e)
  • IndexOutOfBoundsException ex new
  • IndexOutOfBoundsException("M
    sg from metho03")
  • ex.initCause(e)
  • throw ex

Demo ChainedExceptions
19
Reading Stack Traces
  • In meth02 catch block
  • Cause is
  • java.lang.ArithmeticException / by zero
  • In meth01 catch block .
  • In main catch block
  • Print StackTrace
  • ExceptionOne Msg from meth01
  • at Class01.meth01(ChainedExceptions.java27)
  • at ChainedExceptions.main(ChainedExceptions.java
    6)
  • Caused by ExceptionTwo Msg from meth02
  • at Class01.meth02(ChainedExceptions.java39)
  • at Class01.meth01(ChainedExceptions.java21)
  • ... 1 more
  • Caused by java.lang.IndexOutOfBoundsException
    Msg from metho03
  • at Class01.meth03(ChainedExceptions.java47)
  • at Class01.meth02(ChainedExceptions.java33)
  • ... 2 more
  • Caused by java.lang.ArithmeticException / by
    zero
  • at Class01.meth03(ChainedExceptions.java45)

20
Assertions
  • Mechanism to check the correctness of a program
  • Assertions are boolean expression statements
  • Logical statements about the condition or state
    of a program
  • assert h gt 0 h lt 23
  • Executed as normal statements if assertion
    checking is on
  • Typically assertion checking is on during program
    development
  • When assertion checking is on
  • Assertions are evaluated when reached
  • If they evaluate to true the program continues
  • If they evaluate to false program halts and
    AssertionError is thrown
  • When assertion checking is off
  • Assertions evaluate to empty statements
  • Assertion checking is set on by ea flag on JVM
    start

21
Assertion Statement
  • Simple form is
  • assert Expression1
  • where
  • Expression1 is a boolean expression
  • When false system throws an AssertionError with
    no detail message
  • Second form is
  • assert Expression1 Expression2
  • where
  • Expression1 is a boolean expression
  • Expression2 is an expression that has a value and
    cannot have void return
  • Expression2 is passed to AssertionError
    constructor
  • May result is a more detailed information message
  • Assertions may hinder performance
  • Can be disabled

Demo Assertions
22
Stack Tracing Summary
  • Exceptions are error conditions arising in code
    at run time
  • try blocks monitor code blocks, catch blocks
    handle corresponding exceptions
  • finally blocks are always executed and are used
    for cleanup operations
  • catch block can be used to produce a stack trace
  • Shows call stack, descriptive text and line
    numbers where exceptions occurred
  • Can be used to analyze what is the cause of the
    exception
  • Common exceptions in Java code
  • NullpointerException, ClassCastException,
    NumberFormatException
  • Checked exceptions must be handled or declared to
    be thrown
  • Unchecked derived RuntimeException exceptions do
    not have to be handled
  • User defined exceptions can be derived from base
    exceptions
  • Differentiate application specific exceptions
    from other exceptions
  • Assertions check assumptions during development
  • Assertions can be disabled at runtime

Exercise Stack Tracing
Write a Comment
User Comments (0)
About PowerShow.com