SlideShare a Scribd company logo
1 of 27
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

What's hot (20)

Exception Handling In Java
Exception Handling In JavaException Handling In Java
Exception Handling In Java
 
Exception handling
Exception handlingException handling
Exception handling
 
Java chapter 3
Java chapter 3Java chapter 3
Java chapter 3
 
Unit testing - the hard parts
Unit testing - the hard partsUnit testing - the hard parts
Unit testing - the hard parts
 
Exception Handling Mechanism in .NET CLR
Exception Handling Mechanism in .NET CLRException Handling Mechanism in .NET CLR
Exception Handling Mechanism in .NET CLR
 
Exceptions overview
Exceptions overviewExceptions overview
Exceptions overview
 
Exception handling in c++
Exception handling in c++Exception handling in c++
Exception handling in c++
 
Best Practices in Exception Handling
Best Practices in Exception HandlingBest Practices in Exception Handling
Best Practices in Exception Handling
 
Unit 5
Unit 5Unit 5
Unit 5
 
Week7 exception handling
Week7 exception handlingWeek7 exception handling
Week7 exception handling
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Exception Handling In Java 15734
Exception Handling In Java 15734Exception Handling In Java 15734
Exception Handling In Java 15734
 
Exception Handling Java
Exception Handling JavaException Handling Java
Exception Handling Java
 
Java exeception handling
Java exeception handlingJava exeception handling
Java exeception handling
 
Java unit 11
Java unit 11Java unit 11
Java unit 11
 
Python exception handling
Python   exception handlingPython   exception handling
Python exception handling
 
Exception handling in asp.net
Exception handling in asp.netException handling in asp.net
Exception handling in asp.net
 
Exception handling basic
Exception handling basicException handling basic
Exception handling basic
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Presentation1
Presentation1Presentation1
Presentation1
 

Similar to Java Exception Handling

Pi j4.2 software-reliability
Pi j4.2 software-reliabilityPi j4.2 software-reliability
Pi j4.2 software-reliabilitymcollison
 
Chap2 exception handling
Chap2 exception handlingChap2 exception handling
Chap2 exception handlingraksharao
 
Java-Unit 3- Chap2 exception handling
Java-Unit 3- Chap2 exception handlingJava-Unit 3- Chap2 exception handling
Java-Unit 3- Chap2 exception handlingraksharao
 
03 conditions loops
03   conditions loops03   conditions loops
03 conditions loopsManzoor ALam
 
Exceptions in java
Exceptions in javaExceptions in java
Exceptions in javaRajkattamuri
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in javaAdil Mehmoood
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in javapriyankazope
 
Ch-1_5.pdf this is java tutorials for all
Ch-1_5.pdf this is java tutorials for allCh-1_5.pdf this is java tutorials for all
Ch-1_5.pdf this is java tutorials for allHayomeTakele
 
Exception handling in java.pptx
Exception handling in java.pptxException handling in java.pptx
Exception handling in java.pptxARUNPRANESHS
 
Java Exception.ppt
Java Exception.pptJava Exception.ppt
Java Exception.pptRanjithaM32
 
UNIT III 2021R.pptx
UNIT III 2021R.pptxUNIT III 2021R.pptx
UNIT III 2021R.pptxRDeepa9
 
UNIT III 2021R.pptx
UNIT III 2021R.pptxUNIT III 2021R.pptx
UNIT III 2021R.pptxRDeepa9
 
Multi catch statement
Multi catch statementMulti catch statement
Multi catch statementmyrajendra
 
exceptions in java
exceptions in javaexceptions in java
exceptions in javajaveed_mhd
 
C-Programming Control statements.pptx
C-Programming Control statements.pptxC-Programming Control statements.pptx
C-Programming Control statements.pptxSKUP1
 
C-Programming Control statements.pptx
C-Programming Control statements.pptxC-Programming Control statements.pptx
C-Programming Control statements.pptxLECO9
 

Similar to Java Exception Handling (20)

Pi j4.2 software-reliability
Pi j4.2 software-reliabilityPi j4.2 software-reliability
Pi j4.2 software-reliability
 
Chap2 exception handling
Chap2 exception handlingChap2 exception handling
Chap2 exception handling
 
Java-Unit 3- Chap2 exception handling
Java-Unit 3- Chap2 exception handlingJava-Unit 3- Chap2 exception handling
Java-Unit 3- Chap2 exception handling
 
03 conditions loops
03   conditions loops03   conditions loops
03 conditions loops
 
Exceptions in java
Exceptions in javaExceptions in java
Exceptions in java
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
ACP - Week - 9.pptx
ACP - Week - 9.pptxACP - Week - 9.pptx
ACP - Week - 9.pptx
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
 
Ch-1_5.pdf this is java tutorials for all
Ch-1_5.pdf this is java tutorials for allCh-1_5.pdf this is java tutorials for all
Ch-1_5.pdf this is java tutorials for all
 
Exception handling in java.pptx
Exception handling in java.pptxException handling in java.pptx
Exception handling in java.pptx
 
Exceptions.pptx
Exceptions.pptxExceptions.pptx
Exceptions.pptx
 
Java Exception.ppt
Java Exception.pptJava Exception.ppt
Java Exception.ppt
 
UNIT III 2021R.pptx
UNIT III 2021R.pptxUNIT III 2021R.pptx
UNIT III 2021R.pptx
 
UNIT III 2021R.pptx
UNIT III 2021R.pptxUNIT III 2021R.pptx
UNIT III 2021R.pptx
 
Multi catch statement
Multi catch statementMulti catch statement
Multi catch statement
 
exceptions in java
exceptions in javaexceptions in java
exceptions in java
 
C-Programming Control statements.pptx
C-Programming Control statements.pptxC-Programming Control statements.pptx
C-Programming Control statements.pptx
 
C-Programming Control statements.pptx
C-Programming Control statements.pptxC-Programming Control statements.pptx
C-Programming Control statements.pptx
 

More from DeeptiJava

Generating the Server Response: HTTP Status Codes
Generating the Server Response: HTTP Status CodesGenerating the Server Response: HTTP Status Codes
Generating the Server Response: HTTP Status CodesDeeptiJava
 
Java Collection
Java CollectionJava Collection
Java CollectionDeeptiJava
 
Java Access Specifier
Java Access SpecifierJava Access Specifier
Java Access SpecifierDeeptiJava
 
Java Inner Class
Java Inner ClassJava Inner Class
Java Inner ClassDeeptiJava
 
Java Hibernate Basics
Java Hibernate BasicsJava Hibernate Basics
Java Hibernate BasicsDeeptiJava
 
Introduction to Java
Introduction to JavaIntroduction to Java
Introduction to JavaDeeptiJava
 

More from DeeptiJava (13)

Generating the Server Response: HTTP Status Codes
Generating the Server Response: HTTP Status CodesGenerating the Server Response: HTTP Status Codes
Generating the Server Response: HTTP Status Codes
 
Java Generics
Java GenericsJava Generics
Java Generics
 
Java Collection
Java CollectionJava Collection
Java Collection
 
Java OOPs
Java OOPs Java OOPs
Java OOPs
 
Java Access Specifier
Java Access SpecifierJava Access Specifier
Java Access Specifier
 
Java JDBC
Java JDBCJava JDBC
Java JDBC
 
Java Thread
Java ThreadJava Thread
Java Thread
 
Java Inner Class
Java Inner ClassJava Inner Class
Java Inner Class
 
JSP Part 2
JSP Part 2JSP Part 2
JSP Part 2
 
JSP Part 1
JSP Part 1JSP Part 1
JSP Part 1
 
Java I/O
Java I/OJava I/O
Java I/O
 
Java Hibernate Basics
Java Hibernate BasicsJava Hibernate Basics
Java Hibernate Basics
 
Introduction to Java
Introduction to JavaIntroduction to Java
Introduction to Java
 

Recently uploaded

Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024BookNet Canada
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 
Unlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power SystemsUnlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power SystemsPrecisely
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxnull - The Open Security Community
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 

Recently uploaded (20)

Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 
Unlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power SystemsUnlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power Systems
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 

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