'How to create an output when city isn't found in pyowm?

How do I create a custom output on the terminal when a country isn't found (e.g the user misswrote the city)?

The output by default is an error code:

raise exceptions.NotFoundError('Unable to find the resource') pyowm.commons.exceptions.NotFoundError: Unable to find the resource

I'd like the output to be something like:

Sorry, I was unable to find the city you searched for. Please try again...

This is my code so far:

import pyowm

owm = pyowm.OWM('api code')
weather = True

while weather == True:
            weather_input = input('Enter the name of the city you want me to search - ')
            mgr = owm.weather_manager()
            weather_city1 = mgr.weather_at_place(weather_input)
            w = weather_city1.weather
            print('Weather in ' + weather_input + ' - ' + str(w.temperature('celsius')))


Solution 1:[1]

Try with exception handling! A nice Python feature inherited from C-derived languages:

from pyowm import OWM
from pyowm.commons.exceptions import NotFoundError

owm = OWM('api code')
mgr = owm.weather_manager()

while True:
            weather_input = input('Enter the name of the city you want me to search - ')
            try:
                weather_city1 = mgr.weather_at_place(weather_input)
                w = weather_city1.weather
                print('Weather in ' + weather_input + ' - ' + str(w.temperature('celsius')))
            except NotFoundError:
                print('Sorry, I was unable to find the city you searched for. Please try again...')

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 csparpa