xxxxxxxxxx
I use try & catch & finally block
to handle exception if I will use the method
in different class.
Or If I will use it only once and if it is checked
exception then I use THROWS keyword on method signature
xxxxxxxxxx
import sys
try:
f = open('myfile.txt')
s = f.readline()
i = int(s.strip())
except IOError as err:
print("I/O error: {0}".format(err))
except ValueError:
print("Could not convert data to an integer.")
except:
print("Unexpected error:", sys.exc_info()[0])
raise
xxxxxxxxxx
for arg in sys.argv[1:]:
try:
f = open(arg, 'r')
except IOError:
print('cannot open', arg)
else:
print(arg, 'has', len(f.readlines()), 'lines')
f.close()
xxxxxxxxxx
>>> while True:
try:
x = int(input("Please enter a number: "))
break
except ValueError:
print("Oops! That was no valid number. Try again...")
xxxxxxxxxx
>>> try:
raise Exception('spam', 'eggs')
except Exception as inst:
print(type(inst)) # the exception instance
print(inst.args) # arguments stored in .args
print(inst) # __str__ allows args to be printed directly,
# but may be overridden in exception subclasses
x, y = inst.args # unpack args
print('x =', x)
print('y =', y)
<class 'Exception'>
('spam', 'eggs')
('spam', 'eggs')
x = spam
y = eggs
xxxxxxxxxx
>>> def this_fails():
x = 1/0
>>> try:
this_fails()
except ZeroDivisionError as err:
print('Handling run-time error:', err)
Handling run-time error: int division or modulo by zero
xxxxxxxxxx
try:
normal_processing_block
except ExceptionClass as e:
error_processing_block
finally: # optional
final_processing_in_all_cases
xxxxxxxxxx
.flatMap(card -> {
if (Objects.isNull(card.getId())) {
return service.registerCard(mono)
.map(ce -> status(HttpStatus.CREATED)
.body(assembler.entityToModel(ce, exchange)));
} else {
return Mono.error(
() -> new CardAlreadyExistsException(" for user with ID - " + d.getId()));
}
})
Mono<List<String>> monoIds = itemRepo.findByCustomerId( customerId)
.switchIfEmpty(Mono.error(new ResourceNotFoundException(
". No items found in Cart of customer with Id - " + customerId)))
.map(i -> i.getId().toString())
.collectList().cache();
public class ResourceNotFoundException extends RuntimeException
return service.getCartByCustomerId(customerId)
.map(cart ->
assembler.itemfromEntities(cart.getItems().stream()
.filter(i -> i.getProductId().toString(). equals(itemId.trim())).collect(toList()))
.get(0)).map(ResponseEntity::ok)
.onErrorReturn(notFound().build())