Java/J2EE Programming Training
Flow Control, Exceptions, and
Assertions
Page 1Classification: Restricted
Agenda
• Flow Control
• Exceptions
• Assertions
Page 2Classification: Restricted
Objective
• Write code using if and switch statements and identify legal argument
types for these statements.
• Write code using all forms of loops including labeled and unlabeled, use
of break and continue, and state the values taken by loop counter
variables during and after loop execution.
Page 3Classification: Restricted
if – else statements
• The if statement takes a boolean argument, and if the argument is true,
the body of the statement is executed
Eg:
if(x==5) {} // compiles, executes body if x is equal to 5
if(x=0) {} //does not compile, because non-boolean
if(x=true) {} //compiles, but always body is executed
• In the case of nested if-else statements, each else clause belongs to the
closest preceding if statement which does not have an else
Page 4Classification: Restricted
switch statements
• The argument passed to the switch and case statements should be int,
short, char or byte.The argument passed to the case statement should be
a literal or a final variable
• If no case matches, the default statement is executed
• When a break statement is encountered, the control moves out of the
switch statement. If no break statement, all the case statements are
executed till a break is encountered or the switch statement ends
eg: int x=1;
switch(x) {
case 1: System.out.println(“one”);
case 2: System.out.println(“two”);
} // both one and two are printed
Page 5Classification: Restricted
while and do-while loops
• Syntax of while loop is
while(expression) {}
where expression is a boolean expression
• The body of the while loop may not be executed even once
Eg: while(false) {} // body never executed
Eg : while(1) {} // will not compile, not a boolean
• Syntax of do-while loop is
do { } while(expression);
• The body of the do-while loop is executed at least once
Page 6Classification: Restricted
for loop
• The syntax is
for(expr1; expr2; expr3) { body }
where expr1 is for initialization, expr2 is the conditional test and expr3 is
the iteration expression
• Any of these 3 sections can be omitted, still it is legal
Eg: for( ; ; ) {} // an endless loop
• There can be more than one initialization expressions, more than one
iteration expressions, but only one test expression
Page 7Classification: Restricted
break and continue
• break statement is used to exit from a loop or a switch statement
• continue statement is used to stop just the current iteration
• If it is a nested loop, the break statement exits from the innermost loop
only
• If a break keyword is combined with a label, a break statement will exit
out of the labeled loop
eg: outer: for (int i=0;i<10;i++) {
while(y>0){ break outer; }
} // breaks from the for loop if y>0
Page 8Classification: Restricted
Extra points to remember…
• Watch out for boolean assignments(=) that can be mistaken for boolean
equality(==)test:
boolean x=false;
If (x=true) { } // an assignment, so x will always be true
• Switch statements can evaluate only the byte, short, int, and char data
types. You can’t say
long s=30; switch(s) { }
• The default block can be located anywhere in the switch block, so if no
case matches, the default block will be entered, and if the default does
not contain a break, then code will continue to execute (fall-through) to
the end of the switch or until the break statement is encounted.
Page 9Classification: Restricted
Objective
• Write code that makes proper use of exceptions and exception handling
clauses (try, catch, finally) and declares methods and overriding methods
that throw exceptions.
• Recognize the effect of an exception arising at a specified point in a code
fragment. Note: The exception may be a runtime exception, a checked
exception, or an error (the code may include try, catch, or finally clauses
in any legitimate combination).
Page 10Classification: Restricted
Exceptions
• Exceptions in Java are objects, all exceptions are derived from
Throwable class in the java.lang package
• Error, RuntimeException and their subclasses, are unchecked
exceptions. The rest are checked exceptions
• You can create your own exceptions by extending the appropriate
exception class
• Any method that might throw a checked exception must either declare
the exception using the throws keyword, or handle the exception using
a try/catch block
Page 11Classification: Restricted
Exception class hierarchy
Page 12Classification: Restricted
try and catch
• The try block contains the code which might throw an exception, one or
more catch clauses can be provided to handle different exception types
• Eg: try {
// code which might throw exceptions
}
catch(Exception e)
{ //code to handle the exception }
• If an exception is thrown from the try block, the control moves to the catch
block. If there is a matching catch clause, it is executed, else it propagates
through the call stack
Page 13Classification: Restricted
Example
• Eg:
class Test{
public static void main(String args[]) {
try
{
if(x>y)
throw new MyException();
}
catch(Exception e)
{ System.out.println(“caught”+e); }
} }
Page 14Classification: Restricted
Finally
• The finally block is always executed at some point after the try block,
whether an exception is thrown or not
• If no exceptions are thrown from the try block, the finally block is
executed after the try block completes. If an exception is thrown, any
matching catch clauses are executed, after which control comes to the
finally block
• Usage:
try { // code which throws exceptions
}
catch(Exception e){//handle exception}
finally{//clean up code}
Page 15Classification: Restricted
Throws and throw
• The checked exceptions that a method can throw must be declared using
the ‘throws’ keyword
• To throw an exception explicitly from code, use the ‘throw’ keyword
• Eg: /* Assuming MyException is a subclass of Exception*/
void f() throws MyException
{
if(x > y) throw new MyException();
}
• You can also rethrow the same exception which you caught eg:
catch(IOException e) { throw e; }
Page 16Classification: Restricted
Extra points to remember…
• If you throw a checked exception from a catch clause, you must also
declare that exception
• Any method which calls a method which throws a checked exception also
has to declare the exception or handle it
• Unchecked exceptions do not have to be specified or handled using
try/catch
• finally block is executed in all cases except when System.exit() is invoked
• A try block should have either a catch block or a finally block, but its not
compulsory to have both
• All catch blocks must be ordered from the most specific exception to the
most general one
Page 17Classification: Restricted
Objectives
• Write code that makes proper use of assertions, and distinguish
appropriate from inappropriate uses of assertions.
• Identify correct statements about the assertion mechanism.
Page 18Classification: Restricted
Assertions
• An assertion is a statement containing a boolean expression that the
programmer believes to be true at the time the statement is executed.
• Assertions are typically enabled during testing, but disabled during
implementation
• The system executes the assertion by evaluating the boolean expression
and reporting an AssertionError if the expression evaluates to false.
• Eg:
assert(x>0); // throws an AssertionError if x<=0
Page 19Classification: Restricted
Using Assertions
• Assertions can be in two forms
1. assert Expression1 ;
2. assert Expression1 : Expression2 ;
 Expression1 should always result in a boolean value
 Expression2 can be anything which results in a value. The value is
used to generate a String message that displays more debugging
information
Page 20Classification: Restricted
Example
• Eg:
class AssertionTest{
int y,x;
public void func() {
assert (y>x): “y is “+y+”x is “+x ;
// Remaining code
}
}
Page 21Classification: Restricted
Enabling and disabling Assertions
• Assertions are disabled by default
• Enable assertions at compile time using the –source 1.4 flag
eg: javac – source 1.4 TestClass.java
• Enable assertions at runtime using the flag –enableassertions or –ea.
• For selective disabling of assertions at runtime, use the –da or –
disableassertions flag
• For enabling assertions in the system classes, use the –esa or –dsa flags
• Assertions can be enabled or disabled on a package basis also, and
subpackages are automatically included
Page 22Classification: Restricted
When to use Assertions
• Postcondition checks are best implemented via assertions, whether or not
they are in public methods.
• Assertions can be used for precondition checks on nonpublic methods
• Use assertions, even in public methods to check for cases that you know
are never, ever supposed to happen
Eg:
switch(x) {
case 1: z=1;
case 2: z=4;
default: assert false; // Control should never reach
}
Page 23Classification: Restricted
When not to use Assertions
• Do not use assertions to validate arguments to a public method
• Do not use assertions to validate command line arguments
• Do not use assert expressions that will cause side effects
eg:
public void func() {
assert (x++==y); /* Should not be done */
}
This means that an assert expression should leave the program in the
same state it was in before the expression
Page 24Classification: Restricted
Extra points to remember…
• Assertions can be enabled/disabled programmatically or using command
line switches
• Command Line Examples
eg:
java –ea:com.whiz.Test
// Enables assertions in class com.whiz.Test
java –ea –dsa
// Enable assertions, but disable only in system classes
java -ea:com.wombat.fruitbat...
// Enable assertions in com.wombat.fruitbat package and its
subpackages
Page 25Classification: Restricted
Extra points to Remember…
• Curly braces are optional if there is only one statement in the body of if
statement
• The default block can be located anywhere in the switch block, it will be
entered if no case matches
• A variable declared within the for loop declaration cannot be accessed
outside the loop
• The break statement can be used only inside a loop or switch statement,
the continue statement can be used only within a loop
• In a switch case statement, more than one case label using the same
value is not allowed
Page 26Classification: Restricted
Thank You

More Related Content

PPTX
Javasession4
PPT
Exceptionhandling
PPTX
8 Exception Handling
PPT
Understanding Exception Handling in .Net
PPT
Exception handler
PPTX
Exception Handling in Java
PPTX
Java Control Statements
PPTX
What is Exception Handling?
Javasession4
Exceptionhandling
8 Exception Handling
Understanding Exception Handling in .Net
Exception handler
Exception Handling in Java
Java Control Statements
What is Exception Handling?

What's hot (20)

ODP
Exception Handling In Java
PPTX
Exception handling
PPTX
Java chapter 3
PPTX
Unit testing - the hard parts
PPT
Exception Handling Mechanism in .NET CLR
PPTX
Exceptions overview
PPTX
Exception handling in c++
PDF
Best Practices in Exception Handling
PPT
Week7 exception handling
PPTX
Exception handling in java
ODP
Exception Handling In Java 15734
PPT
Exception Handling Java
PDF
Java unit 11
PDF
Python exception handling
PPTX
Exception handling in asp.net
PDF
Exception handling basic
PPTX
Exception handling in java
PPTX
Presentation1
Exception Handling In Java
Exception handling
Java chapter 3
Unit testing - the hard parts
Exception Handling Mechanism in .NET CLR
Exceptions overview
Exception handling in c++
Best Practices in Exception Handling
Week7 exception handling
Exception handling in java
Exception Handling In Java 15734
Exception Handling Java
Java unit 11
Python exception handling
Exception handling in asp.net
Exception handling basic
Exception handling in java
Presentation1
Ad

Similar to Java Exception Handling (20)

PPTX
Pi j4.2 software-reliability
PPTX
Java-Unit 3- Chap2 exception handling
PPTX
Chap2 exception handling
PPT
03 conditions loops
PPT
Exceptions in java
PPTX
Exception handling in java
PPTX
ACP - Week - 9.pptx
ODP
Exception handling in java
PPTX
Java exception handling
PDF
Ch-1_5.pdf this is java tutorials for all
PPTX
Exception handling in java.pptx
PPTX
Exceptions.pptx
PPT
Java Exception.ppt
PPTX
UNIT III 2021R.pptx
PPTX
UNIT III 2021R.pptx
PPT
Multi catch statement
PPT
exceptions in java
PPTX
C-Programming Control statements.pptx
PPTX
C-Programming Control statements.pptx
Pi j4.2 software-reliability
Java-Unit 3- Chap2 exception handling
Chap2 exception handling
03 conditions loops
Exceptions in java
Exception handling in java
ACP - Week - 9.pptx
Exception handling in java
Java exception handling
Ch-1_5.pdf this is java tutorials for all
Exception handling in java.pptx
Exceptions.pptx
Java Exception.ppt
UNIT III 2021R.pptx
UNIT III 2021R.pptx
Multi catch statement
exceptions in java
C-Programming Control statements.pptx
C-Programming Control statements.pptx
Ad

More from DeeptiJava (13)

PPT
Generating the Server Response: HTTP Status Codes
PPTX
Java Generics
PPTX
Java Collection
PPTX
Java OOPs
PPTX
Java Access Specifier
PPTX
Java JDBC
PPTX
Java Thread
PPTX
Java Inner Class
PPT
JSP Part 2
PPT
JSP Part 1
PPTX
Java I/O
PPT
Java Hibernate Basics
PPTX
Introduction to Java
Generating the Server Response: HTTP Status Codes
Java Generics
Java Collection
Java OOPs
Java Access Specifier
Java JDBC
Java Thread
Java Inner Class
JSP Part 2
JSP Part 1
Java I/O
Java Hibernate Basics
Introduction to Java

Recently uploaded (20)

PDF
NewMind AI Journal Monthly Chronicles - August 2025
PPTX
From XAI to XEE through Influence and Provenance.Controlling model fairness o...
PDF
Introduction to c language from lecture slides
PDF
Altius execution marketplace concept.pdf
PDF
Be ready for tomorrow’s needs with a longer-lasting, higher-performing PC
PDF
GDG Cloud Southlake #45: Patrick Debois: The Impact of GenAI on Development a...
PDF
Decision Optimization - From Theory to Practice
PDF
State of AI in Business 2025 - MIT NANDA
PPTX
maintenance powerrpoint for adaprive and preventive
PDF
Rooftops detection with YOLOv8 from aerial imagery and a brief review on roof...
PPTX
AQUEEL MUSHTAQUE FAKIH COMPUTER CENTER .
PDF
“Introduction to Designing with AI Agents,” a Presentation from Amazon Web Se...
PPT
Overviiew on Intellectual property right
PDF
1_Keynote_Breaking Barriers_한계를 넘어서_Charith Mendis.pdf
PPTX
Blending method and technology for hydrogen.pptx
PPTX
Report in SIP_Distance_Learning_Technology_Impact.pptx
PDF
FASHION-DRIVEN TEXTILES AS A CRYSTAL OF A NEW STREAM FOR STAKEHOLDER CAPITALI...
PPTX
Slides World Game (s) Great Redesign Eco Economic Epochs.pptx
PPTX
Strategic Picks — Prioritising the Right Agentic Use Cases [2/6]
PDF
Slides World Game (s) Great Redesign Eco Economic Epochs.pdf
NewMind AI Journal Monthly Chronicles - August 2025
From XAI to XEE through Influence and Provenance.Controlling model fairness o...
Introduction to c language from lecture slides
Altius execution marketplace concept.pdf
Be ready for tomorrow’s needs with a longer-lasting, higher-performing PC
GDG Cloud Southlake #45: Patrick Debois: The Impact of GenAI on Development a...
Decision Optimization - From Theory to Practice
State of AI in Business 2025 - MIT NANDA
maintenance powerrpoint for adaprive and preventive
Rooftops detection with YOLOv8 from aerial imagery and a brief review on roof...
AQUEEL MUSHTAQUE FAKIH COMPUTER CENTER .
“Introduction to Designing with AI Agents,” a Presentation from Amazon Web Se...
Overviiew on Intellectual property right
1_Keynote_Breaking Barriers_한계를 넘어서_Charith Mendis.pdf
Blending method and technology for hydrogen.pptx
Report in SIP_Distance_Learning_Technology_Impact.pptx
FASHION-DRIVEN TEXTILES AS A CRYSTAL OF A NEW STREAM FOR STAKEHOLDER CAPITALI...
Slides World Game (s) Great Redesign Eco Economic Epochs.pptx
Strategic Picks — Prioritising the Right Agentic Use Cases [2/6]
Slides World Game (s) Great Redesign Eco Economic Epochs.pdf

Java Exception Handling

  • 1. Java/J2EE Programming Training Flow Control, Exceptions, and Assertions
  • 2. Page 1Classification: Restricted Agenda • Flow Control • Exceptions • Assertions
  • 3. Page 2Classification: Restricted Objective • Write code using if and switch statements and identify legal argument types for these statements. • Write code using all forms of loops including labeled and unlabeled, use of break and continue, and state the values taken by loop counter variables during and after loop execution.
  • 4. Page 3Classification: Restricted if – else statements • The if statement takes a boolean argument, and if the argument is true, the body of the statement is executed Eg: if(x==5) {} // compiles, executes body if x is equal to 5 if(x=0) {} //does not compile, because non-boolean if(x=true) {} //compiles, but always body is executed • In the case of nested if-else statements, each else clause belongs to the closest preceding if statement which does not have an else
  • 5. Page 4Classification: Restricted switch statements • The argument passed to the switch and case statements should be int, short, char or byte.The argument passed to the case statement should be a literal or a final variable • If no case matches, the default statement is executed • When a break statement is encountered, the control moves out of the switch statement. If no break statement, all the case statements are executed till a break is encountered or the switch statement ends eg: int x=1; switch(x) { case 1: System.out.println(“one”); case 2: System.out.println(“two”); } // both one and two are printed
  • 6. Page 5Classification: Restricted while and do-while loops • Syntax of while loop is while(expression) {} where expression is a boolean expression • The body of the while loop may not be executed even once Eg: while(false) {} // body never executed Eg : while(1) {} // will not compile, not a boolean • Syntax of do-while loop is do { } while(expression); • The body of the do-while loop is executed at least once
  • 7. Page 6Classification: Restricted for loop • The syntax is for(expr1; expr2; expr3) { body } where expr1 is for initialization, expr2 is the conditional test and expr3 is the iteration expression • Any of these 3 sections can be omitted, still it is legal Eg: for( ; ; ) {} // an endless loop • There can be more than one initialization expressions, more than one iteration expressions, but only one test expression
  • 8. Page 7Classification: Restricted break and continue • break statement is used to exit from a loop or a switch statement • continue statement is used to stop just the current iteration • If it is a nested loop, the break statement exits from the innermost loop only • If a break keyword is combined with a label, a break statement will exit out of the labeled loop eg: outer: for (int i=0;i<10;i++) { while(y>0){ break outer; } } // breaks from the for loop if y>0
  • 9. Page 8Classification: Restricted Extra points to remember… • Watch out for boolean assignments(=) that can be mistaken for boolean equality(==)test: boolean x=false; If (x=true) { } // an assignment, so x will always be true • Switch statements can evaluate only the byte, short, int, and char data types. You can’t say long s=30; switch(s) { } • The default block can be located anywhere in the switch block, so if no case matches, the default block will be entered, and if the default does not contain a break, then code will continue to execute (fall-through) to the end of the switch or until the break statement is encounted.
  • 10. Page 9Classification: Restricted Objective • Write code that makes proper use of exceptions and exception handling clauses (try, catch, finally) and declares methods and overriding methods that throw exceptions. • Recognize the effect of an exception arising at a specified point in a code fragment. Note: The exception may be a runtime exception, a checked exception, or an error (the code may include try, catch, or finally clauses in any legitimate combination).
  • 11. Page 10Classification: Restricted Exceptions • Exceptions in Java are objects, all exceptions are derived from Throwable class in the java.lang package • Error, RuntimeException and their subclasses, are unchecked exceptions. The rest are checked exceptions • You can create your own exceptions by extending the appropriate exception class • Any method that might throw a checked exception must either declare the exception using the throws keyword, or handle the exception using a try/catch block
  • 13. Page 12Classification: Restricted try and catch • The try block contains the code which might throw an exception, one or more catch clauses can be provided to handle different exception types • Eg: try { // code which might throw exceptions } catch(Exception e) { //code to handle the exception } • If an exception is thrown from the try block, the control moves to the catch block. If there is a matching catch clause, it is executed, else it propagates through the call stack
  • 14. Page 13Classification: Restricted Example • Eg: class Test{ public static void main(String args[]) { try { if(x>y) throw new MyException(); } catch(Exception e) { System.out.println(“caught”+e); } } }
  • 15. Page 14Classification: Restricted Finally • The finally block is always executed at some point after the try block, whether an exception is thrown or not • If no exceptions are thrown from the try block, the finally block is executed after the try block completes. If an exception is thrown, any matching catch clauses are executed, after which control comes to the finally block • Usage: try { // code which throws exceptions } catch(Exception e){//handle exception} finally{//clean up code}
  • 16. Page 15Classification: Restricted Throws and throw • The checked exceptions that a method can throw must be declared using the ‘throws’ keyword • To throw an exception explicitly from code, use the ‘throw’ keyword • Eg: /* Assuming MyException is a subclass of Exception*/ void f() throws MyException { if(x > y) throw new MyException(); } • You can also rethrow the same exception which you caught eg: catch(IOException e) { throw e; }
  • 17. Page 16Classification: Restricted Extra points to remember… • If you throw a checked exception from a catch clause, you must also declare that exception • Any method which calls a method which throws a checked exception also has to declare the exception or handle it • Unchecked exceptions do not have to be specified or handled using try/catch • finally block is executed in all cases except when System.exit() is invoked • A try block should have either a catch block or a finally block, but its not compulsory to have both • All catch blocks must be ordered from the most specific exception to the most general one
  • 18. Page 17Classification: Restricted Objectives • Write code that makes proper use of assertions, and distinguish appropriate from inappropriate uses of assertions. • Identify correct statements about the assertion mechanism.
  • 19. Page 18Classification: Restricted Assertions • An assertion is a statement containing a boolean expression that the programmer believes to be true at the time the statement is executed. • Assertions are typically enabled during testing, but disabled during implementation • The system executes the assertion by evaluating the boolean expression and reporting an AssertionError if the expression evaluates to false. • Eg: assert(x>0); // throws an AssertionError if x<=0
  • 20. Page 19Classification: Restricted Using Assertions • Assertions can be in two forms 1. assert Expression1 ; 2. assert Expression1 : Expression2 ;  Expression1 should always result in a boolean value  Expression2 can be anything which results in a value. The value is used to generate a String message that displays more debugging information
  • 21. Page 20Classification: Restricted Example • Eg: class AssertionTest{ int y,x; public void func() { assert (y>x): “y is “+y+”x is “+x ; // Remaining code } }
  • 22. Page 21Classification: Restricted Enabling and disabling Assertions • Assertions are disabled by default • Enable assertions at compile time using the –source 1.4 flag eg: javac – source 1.4 TestClass.java • Enable assertions at runtime using the flag –enableassertions or –ea. • For selective disabling of assertions at runtime, use the –da or – disableassertions flag • For enabling assertions in the system classes, use the –esa or –dsa flags • Assertions can be enabled or disabled on a package basis also, and subpackages are automatically included
  • 23. Page 22Classification: Restricted When to use Assertions • Postcondition checks are best implemented via assertions, whether or not they are in public methods. • Assertions can be used for precondition checks on nonpublic methods • Use assertions, even in public methods to check for cases that you know are never, ever supposed to happen Eg: switch(x) { case 1: z=1; case 2: z=4; default: assert false; // Control should never reach }
  • 24. Page 23Classification: Restricted When not to use Assertions • Do not use assertions to validate arguments to a public method • Do not use assertions to validate command line arguments • Do not use assert expressions that will cause side effects eg: public void func() { assert (x++==y); /* Should not be done */ } This means that an assert expression should leave the program in the same state it was in before the expression
  • 25. Page 24Classification: Restricted Extra points to remember… • Assertions can be enabled/disabled programmatically or using command line switches • Command Line Examples eg: java –ea:com.whiz.Test // Enables assertions in class com.whiz.Test java –ea –dsa // Enable assertions, but disable only in system classes java -ea:com.wombat.fruitbat... // Enable assertions in com.wombat.fruitbat package and its subpackages
  • 26. Page 25Classification: Restricted Extra points to Remember… • Curly braces are optional if there is only one statement in the body of if statement • The default block can be located anywhere in the switch block, it will be entered if no case matches • A variable declared within the for loop declaration cannot be accessed outside the loop • The break statement can be used only inside a loop or switch statement, the continue statement can be used only within a loop • In a switch case statement, more than one case label using the same value is not allowed