SlideShare a Scribd company logo
1 of 13
Java Session 4
Flow control & Exceptions
•
•
•
•
•
•
•

If and Switch statement
Loops- While, Do, For
Break and continue
Labeled and unlabeled statements
Exceptions
Try.. Catch.. Finally
Propagating and catching exceptions
If statement
• if statement is decision statement.
• Basic format of an if statement :
if (booleanExpression)

{

System.out.println("Inside if statement");

}
•

The expression in parentheses must evaluate to (a boolean) true or false.

• Sun considers it good practice to enclose blocks within curly braces, even if
there's only one statement in the block.

• Remember that the only legal expression in an if test is a boolean.
• Refer examples : https://gist.github.com/rajeevprasanna/8893069
Switch statement
•

A way to simulate the use of multiple if statements is with the switch statement.

•

The general form of the switch statement : break statements are optional
switch (expression) {
case constant1: code block
case constant2: code block
default: code block
}

•

A switch's expression must evaluate to a char, byte, short, int, or, as of Java 6, an enum. If you're
not using an enum, only variables and values that can be automatically promoted (in other words,
implicitly cast) to an int are acceptable. You won't be able to compile if you use anything.

•

A case constant must evaluate to the same type as the switch expression can use, with one
additional—and big—constraint: the case constant must be a compile time constant!

•

Compile time constant must be declared final,primitive or String,initialized within
declaration,initialized with constant expression

•

Case constants are evaluated from the top down, and the first case constant that matches the switch's
expression is the execution entry point.

•

The default case doesn’t have to come at the end of the switch.

•

Refer examples here : https://gist.github.com/rajeevprasanna/8893481
Loops

•

While loops : The while loop is good for scenarios where you don't know how many times a block or
statement should repeat, but you want to continue looping as long as some condition is true.

•

Do Loops : The do loop is similar to the while loop, except that the expression is not evaluated until
after the do loop's code is executed. Therefore the code in a do loop is guaranteed to execute at least
once.

•

For loops : The for loop is especially useful for flow control when you already know how many
times you need to execute the statements in the loop's block.

•

The for loop declaration has three main parts, besides the body of the loop :
 Declaration and initialization of variables, The boolean expression (conditional test), The
iteration expression

 for (/*Initialization*/ ; /*Condition*/ ; /* Iteration */) { /* loop body */ }
•

Keep in mind that barring a forced exit, evaluating the iteration expression and then evaluating the
conditional expression are always the last two things that happen in a for loop!

•

Enhanced For loop : for(declaration : expression)
 declaration The newly declared block variable, of a type compatible with the elements of the
array you are accessing. This variable will be available within the for block, and its value will
be the same as the current array element.


•

expression This must evaluate to the array you want to loop through. This could be an array
variable or a method call that returns an array. The array can be any type: primitives, objects,
even arrays of arrays.

Refer example here : https://gist.github.com/rajeevprasanna/8893936
Break, Continue & Label statements
•

Forced exits include a break, a return, a System.exit(), or an exception, which will all cause a loop to
terminate abruptly, without running the iteration expression.

•

break : Execution jumps immediately to the 1st statement after the for loop. The break
statement causes the program to stop execution of the innermost loop and start processing
the next line of code after the block.

•

return : Execution jumps immediately back to the calling method.

•

System.exit() : All program execution stops; the VM shuts down.

•

Refer examples here : https://gist.github.com/rajeevprasanna/8894100

 Labeled statements :
•

Labeled continue and break statements must be inside the loop that has the same label name;
otherwise, the code will not compile.

•

Refer examples here : https://gist.github.com/rajeevprasanna/8894161
Exceptions
•

The term "exception" means "exceptional condition" and is an occurrence that alters the normal
program flow.

•

Exception handling works by transferring the execution of a program to an appropriate exception
handler when an exception occurs.

•

Tell the JVM what code to execute when a certain exception happens. To do this, we use the try and
catch keywords.

•

Finally : A finally block encloses code that is always executed at some point after the try block,
whether an exception was thrown or not. Even if there is a return statement in the try block, the
finally block executes right after the return statement is encountered, and before the return executes.

•

Finally block is the right place to close your files, release your network sockets, and perform any
other cleanup your code requires.

•

If the try block executes with no exceptions, the finally block is executed immediately after the try
block completes.

•

If there was an exception thrown, the finally block executes immediately after the proper catch block
completes.

•

Finally clauses are optional. If you don't write one, your code will compile and run just fine. In fact, if
you have no resources to clean up after your try block completes, you probably don't need a finally
clause.

•

Try, catch, or finally blocks don't share any code. They are independent of each other.

•

It is legal to omit either the catch clause or the finally clause, but not both.
Exception hierarchy
•

Any unhandled exception will prop up across the stack.

•

An exception that's never caught will cause your application to stop running.

•

All exceptions are sub classes of Exception class.

•

Classes that derive from Error represent unusual situations that are not caused by program errors, and
indicate things that would not normally happen during program execution, such as the JVM running
out of memory. Generally, your application won't be able to recover from an Error, so you're not
required to handle them.

•

Errors are technically not exceptions because they do not derive from class Exception.

•

Exception hierarchy :
Exceptions(Contd …)
•

The java.lang.Throwable class is the superclass of all errors and exceptions in the Java language.
Only objects that are instances of this class (or one of its subclasses) are thrown by the Java Virtual
Machine or can be thrown by the Java throw statement.

•

You can actually catch more than one type of exception in a single catch clause. If the exception class
that you specify in the catch clause has no subclasses, then only the specified class of exception will
be caught. However, if the class specified in the catch clause does have subclasses, any exception
object that subclasses the specified class will be caught as well.

•

By specifying an exception class's superclass in your catch clause, you're discarding valuable
information about the exception. You can, of course, find out exactly what exception class you have,
but if you're going to do that, you're better off writing a separate catch clause for each exception type
of interest.

•

The handlers for the most specific exceptions must always be placed above those for more general
exceptions.

•

If one Exception class is not a subtype or supertype of the other, then the order in which the catch
clauses are placed doesn't matter.
Checked and Unchecked Exceptions
•

Checked Exceptions : Checked are the exceptions that are checked at compile time. The compiler
checks to make sure that they're handled or declared. If some code within a method throws a checked
exception, then the method must either handle the exception or it must specify the exception using
throws keyword.

•

Un Checked Exceptions : Unchecked are the exceptions that are not checked at compiled time.
Exceptions under Error and RuntimeException classes are unchecked exceptions, everything else
under throwable is checked.

•

Java compiler doesn’t forces un checked exceptions to be declared. An object of type
RuntimeException may be thrown from any method without being specified as part of the method's
public interface (and a handler need not be present). And even if a method does declare a
RuntimeException, the calling method is under no obligation to handle or declare it.
RuntimeException, Error, and all of their subtypes are unchecked exceptions and unchecked
exceptions do not have to be specified or handled.

•

Examples of Unchecked exceptions : OutOfMemoryError, NullPointerException etc

•

The runtime exception classes (RuntimeException and its subclasses) are exempted from compiletime checking because, in the judgment of the designers of the Java, having to declare such
exceptions would not aid significantly in establishing the correctness of programs.

•

Each method must either handle all checked exceptions by supplying a catch clause or list each
unhandled checked exception as a thrown exception.
Writing own Exceptions
•

To create your own exception, you simply subclass Exception (or one of its subclasses)
Ex : class MyException extends Exception { }

•

Error is not a subtype of Exception, it doesn't need to be declared. You're free to declare it if you like,
but the compiler just doesn't care one way or another when or how the Error is thrown, or by whom.

•

Rethrowing the Same Exception: We can rethrow the same exception after doing some activities.

•

Where Exceptions Come From:
• JVM exceptions : Those exceptions or errors that are either exclusively or most logically thrown
by the JVM.
• Programmatic exceptions : Those exceptions that are thrown explicitly by application and/or
API programmers.

Refer examples here: https://gist.github.com/rajeevprasanna/8894887
Common Exceptions
Javasession4

More Related Content

What's hot

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
 
Exception handling in java
Exception handling  in javaException handling  in java
Exception handling in java
 
Exceptions overview
Exceptions overviewExceptions overview
Exceptions overview
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
 
Exception Handling In Java
Exception Handling In JavaException Handling In Java
Exception Handling In Java
 
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
 
Exception Handling Java
Exception Handling JavaException Handling Java
Exception Handling Java
 
Exception handling in java
Exception handling  in javaException handling  in java
Exception handling in java
 
Java Exception Handling and Applets
Java Exception Handling and AppletsJava Exception Handling and Applets
Java Exception Handling and Applets
 
Java: Exception
Java: ExceptionJava: Exception
Java: Exception
 
Md07 exceptions&assertion
Md07 exceptions&assertionMd07 exceptions&assertion
Md07 exceptions&assertion
 
Exception Handling In Java 15734
Exception Handling In Java 15734Exception Handling In Java 15734
Exception Handling In Java 15734
 
exception handling
exception handlingexception handling
exception handling
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
 
Exception handling in JAVA
Exception handling in JAVAException handling in JAVA
Exception handling in JAVA
 
Exception Handling in Java
Exception Handling in JavaException Handling in Java
Exception Handling in Java
 
Java unit 11
Java unit 11Java unit 11
Java unit 11
 
javaexceptions
javaexceptionsjavaexceptions
javaexceptions
 

Similar to Javasession4

Java-Unit 3- Chap2 exception handling
Java-Unit 3- Chap2 exception handlingJava-Unit 3- Chap2 exception handling
Java-Unit 3- Chap2 exception handlingraksharao
 
Exception handling in java.pptx
Exception handling in java.pptxException handling in java.pptx
Exception handling in java.pptxARUNPRANESHS
 
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
 
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
 
Java Exceptions and Exception Handling
 Java  Exceptions and Exception Handling Java  Exceptions and Exception Handling
Java Exceptions and Exception HandlingMaqdamYasir
 
A36519192_21789_4_2018_Exception Handling.ppt
A36519192_21789_4_2018_Exception Handling.pptA36519192_21789_4_2018_Exception Handling.ppt
A36519192_21789_4_2018_Exception Handling.pptpromila09
 
exception handling in java.ppt
exception handling in java.pptexception handling in java.ppt
exception handling in java.pptVarshini62
 
Exceptions in java
Exceptions in javaExceptions in java
Exceptions in javaRajkattamuri
 
Introduction to java exceptions
Introduction to java exceptionsIntroduction to java exceptions
Introduction to java exceptionsSujit Kumar
 
Exception handling in java-PPT.pptx
Exception handling in java-PPT.pptxException handling in java-PPT.pptx
Exception handling in java-PPT.pptxsonalipatil225940
 
Exception handling chapter15
Exception handling chapter15Exception handling chapter15
Exception handling chapter15Kumar
 
Multi catch statement
Multi catch statementMulti catch statement
Multi catch statementmyrajendra
 
Exception Handling.pptx
Exception Handling.pptxException Handling.pptx
Exception Handling.pptxprimevideos176
 
Exception handling
Exception handlingException handling
Exception handlingpooja kumari
 

Similar to Javasession4 (20)

Java-Unit 3- Chap2 exception handling
Java-Unit 3- Chap2 exception handlingJava-Unit 3- Chap2 exception handling
Java-Unit 3- Chap2 exception handling
 
Exception handling in java.pptx
Exception handling in java.pptxException handling in java.pptx
Exception handling in java.pptx
 
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
 
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
 
Exception handling in .net
Exception handling in .netException handling in .net
Exception handling in .net
 
Exception handling in ASP .NET
Exception handling in ASP .NETException handling in ASP .NET
Exception handling in ASP .NET
 
Java Exceptions and Exception Handling
 Java  Exceptions and Exception Handling Java  Exceptions and Exception Handling
Java Exceptions and Exception Handling
 
A36519192_21789_4_2018_Exception Handling.ppt
A36519192_21789_4_2018_Exception Handling.pptA36519192_21789_4_2018_Exception Handling.ppt
A36519192_21789_4_2018_Exception Handling.ppt
 
exception handling in java.ppt
exception handling in java.pptexception handling in java.ppt
exception handling in java.ppt
 
Exceptions in java
Exceptions in javaExceptions in java
Exceptions in java
 
Introduction to java exceptions
Introduction to java exceptionsIntroduction to java exceptions
Introduction to java exceptions
 
Exception
ExceptionException
Exception
 
Exception handling in java-PPT.pptx
Exception handling in java-PPT.pptxException handling in java-PPT.pptx
Exception handling in java-PPT.pptx
 
Exception handling chapter15
Exception handling chapter15Exception handling chapter15
Exception handling chapter15
 
Exception handling basic
Exception handling basicException handling basic
Exception handling basic
 
Multi catch statement
Multi catch statementMulti catch statement
Multi catch statement
 
Exception Handling.pptx
Exception Handling.pptxException Handling.pptx
Exception Handling.pptx
 
Java exeception handling
Java exeception handlingJava exeception handling
Java exeception handling
 
Exception handling
Exception handlingException handling
Exception handling
 

More from Rajeev Kumar

More from Rajeev Kumar (9)

Db performance optimization with indexing
Db performance optimization with indexingDb performance optimization with indexing
Db performance optimization with indexing
 
Javasession10
Javasession10Javasession10
Javasession10
 
Jms intro
Jms introJms intro
Jms intro
 
Javasession8
Javasession8Javasession8
Javasession8
 
Javasession6
Javasession6Javasession6
Javasession6
 
Javasession7
Javasession7Javasession7
Javasession7
 
Javasession5
Javasession5Javasession5
Javasession5
 
Java session 3
Java session 3Java session 3
Java session 3
 
Java session2
Java session2Java session2
Java session2
 

Recently uploaded

Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxBkGupta21
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESmohitsingh558521
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 

Recently uploaded (20)

Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptx
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 

Javasession4

  • 2. Flow control & Exceptions • • • • • • • If and Switch statement Loops- While, Do, For Break and continue Labeled and unlabeled statements Exceptions Try.. Catch.. Finally Propagating and catching exceptions
  • 3. If statement • if statement is decision statement. • Basic format of an if statement : if (booleanExpression) { System.out.println("Inside if statement"); } • The expression in parentheses must evaluate to (a boolean) true or false. • Sun considers it good practice to enclose blocks within curly braces, even if there's only one statement in the block. • Remember that the only legal expression in an if test is a boolean. • Refer examples : https://gist.github.com/rajeevprasanna/8893069
  • 4. Switch statement • A way to simulate the use of multiple if statements is with the switch statement. • The general form of the switch statement : break statements are optional switch (expression) { case constant1: code block case constant2: code block default: code block } • A switch's expression must evaluate to a char, byte, short, int, or, as of Java 6, an enum. If you're not using an enum, only variables and values that can be automatically promoted (in other words, implicitly cast) to an int are acceptable. You won't be able to compile if you use anything. • A case constant must evaluate to the same type as the switch expression can use, with one additional—and big—constraint: the case constant must be a compile time constant! • Compile time constant must be declared final,primitive or String,initialized within declaration,initialized with constant expression • Case constants are evaluated from the top down, and the first case constant that matches the switch's expression is the execution entry point. • The default case doesn’t have to come at the end of the switch. • Refer examples here : https://gist.github.com/rajeevprasanna/8893481
  • 5. Loops • While loops : The while loop is good for scenarios where you don't know how many times a block or statement should repeat, but you want to continue looping as long as some condition is true. • Do Loops : The do loop is similar to the while loop, except that the expression is not evaluated until after the do loop's code is executed. Therefore the code in a do loop is guaranteed to execute at least once. • For loops : The for loop is especially useful for flow control when you already know how many times you need to execute the statements in the loop's block. • The for loop declaration has three main parts, besides the body of the loop :  Declaration and initialization of variables, The boolean expression (conditional test), The iteration expression  for (/*Initialization*/ ; /*Condition*/ ; /* Iteration */) { /* loop body */ } • Keep in mind that barring a forced exit, evaluating the iteration expression and then evaluating the conditional expression are always the last two things that happen in a for loop! • Enhanced For loop : for(declaration : expression)  declaration The newly declared block variable, of a type compatible with the elements of the array you are accessing. This variable will be available within the for block, and its value will be the same as the current array element.  • expression This must evaluate to the array you want to loop through. This could be an array variable or a method call that returns an array. The array can be any type: primitives, objects, even arrays of arrays. Refer example here : https://gist.github.com/rajeevprasanna/8893936
  • 6. Break, Continue & Label statements • Forced exits include a break, a return, a System.exit(), or an exception, which will all cause a loop to terminate abruptly, without running the iteration expression. • break : Execution jumps immediately to the 1st statement after the for loop. The break statement causes the program to stop execution of the innermost loop and start processing the next line of code after the block. • return : Execution jumps immediately back to the calling method. • System.exit() : All program execution stops; the VM shuts down. • Refer examples here : https://gist.github.com/rajeevprasanna/8894100  Labeled statements : • Labeled continue and break statements must be inside the loop that has the same label name; otherwise, the code will not compile. • Refer examples here : https://gist.github.com/rajeevprasanna/8894161
  • 7. Exceptions • The term "exception" means "exceptional condition" and is an occurrence that alters the normal program flow. • Exception handling works by transferring the execution of a program to an appropriate exception handler when an exception occurs. • Tell the JVM what code to execute when a certain exception happens. To do this, we use the try and catch keywords. • Finally : A finally block encloses code that is always executed at some point after the try block, whether an exception was thrown or not. Even if there is a return statement in the try block, the finally block executes right after the return statement is encountered, and before the return executes. • Finally block is the right place to close your files, release your network sockets, and perform any other cleanup your code requires. • If the try block executes with no exceptions, the finally block is executed immediately after the try block completes. • If there was an exception thrown, the finally block executes immediately after the proper catch block completes. • Finally clauses are optional. If you don't write one, your code will compile and run just fine. In fact, if you have no resources to clean up after your try block completes, you probably don't need a finally clause. • Try, catch, or finally blocks don't share any code. They are independent of each other. • It is legal to omit either the catch clause or the finally clause, but not both.
  • 8. Exception hierarchy • Any unhandled exception will prop up across the stack. • An exception that's never caught will cause your application to stop running. • All exceptions are sub classes of Exception class. • Classes that derive from Error represent unusual situations that are not caused by program errors, and indicate things that would not normally happen during program execution, such as the JVM running out of memory. Generally, your application won't be able to recover from an Error, so you're not required to handle them. • Errors are technically not exceptions because they do not derive from class Exception. • Exception hierarchy :
  • 9. Exceptions(Contd …) • The java.lang.Throwable class is the superclass of all errors and exceptions in the Java language. Only objects that are instances of this class (or one of its subclasses) are thrown by the Java Virtual Machine or can be thrown by the Java throw statement. • You can actually catch more than one type of exception in a single catch clause. If the exception class that you specify in the catch clause has no subclasses, then only the specified class of exception will be caught. However, if the class specified in the catch clause does have subclasses, any exception object that subclasses the specified class will be caught as well. • By specifying an exception class's superclass in your catch clause, you're discarding valuable information about the exception. You can, of course, find out exactly what exception class you have, but if you're going to do that, you're better off writing a separate catch clause for each exception type of interest. • The handlers for the most specific exceptions must always be placed above those for more general exceptions. • If one Exception class is not a subtype or supertype of the other, then the order in which the catch clauses are placed doesn't matter.
  • 10. Checked and Unchecked Exceptions • Checked Exceptions : Checked are the exceptions that are checked at compile time. The compiler checks to make sure that they're handled or declared. If some code within a method throws a checked exception, then the method must either handle the exception or it must specify the exception using throws keyword. • Un Checked Exceptions : Unchecked are the exceptions that are not checked at compiled time. Exceptions under Error and RuntimeException classes are unchecked exceptions, everything else under throwable is checked. • Java compiler doesn’t forces un checked exceptions to be declared. An object of type RuntimeException may be thrown from any method without being specified as part of the method's public interface (and a handler need not be present). And even if a method does declare a RuntimeException, the calling method is under no obligation to handle or declare it. RuntimeException, Error, and all of their subtypes are unchecked exceptions and unchecked exceptions do not have to be specified or handled. • Examples of Unchecked exceptions : OutOfMemoryError, NullPointerException etc • The runtime exception classes (RuntimeException and its subclasses) are exempted from compiletime checking because, in the judgment of the designers of the Java, having to declare such exceptions would not aid significantly in establishing the correctness of programs. • Each method must either handle all checked exceptions by supplying a catch clause or list each unhandled checked exception as a thrown exception.
  • 11. Writing own Exceptions • To create your own exception, you simply subclass Exception (or one of its subclasses) Ex : class MyException extends Exception { } • Error is not a subtype of Exception, it doesn't need to be declared. You're free to declare it if you like, but the compiler just doesn't care one way or another when or how the Error is thrown, or by whom. • Rethrowing the Same Exception: We can rethrow the same exception after doing some activities. • Where Exceptions Come From: • JVM exceptions : Those exceptions or errors that are either exclusively or most logically thrown by the JVM. • Programmatic exceptions : Those exceptions that are thrown explicitly by application and/or API programmers. Refer examples here: https://gist.github.com/rajeevprasanna/8894887